finished text scaling code

pull/1/head
Sara 2023-04-23 00:47:35 +02:00
parent 5686c17fee
commit 3c3c565bfa
2 changed files with 24 additions and 20 deletions

View File

@ -1,9 +1,16 @@
# TODOs # TODOs
[ ] add nineslice drawcmd functions [x] add nineslice drawcmd functions
[x] draw_* [x] draw_*
[x] exec_* [x] exec_*
[ ] add text rendering
[x] loading fonts
[x] managing font style
[x] rendering fonts to surface to texture
[x] correctly scaling fonts
[ ] cache rendered text
[ ] add imgui [ ] add imgui
[ ] ui windows [ ] ui windows
[ ] input fields [ ] input fields

View File

@ -4,10 +4,11 @@
#include "layers.h" #include "layers.h"
#include "signal.h" #include "signal.h"
#include "inttypes.h" #include "inttypes.h"
#include "string.h"
#include "SDL2/SDL_blendmode.h" #include "SDL2/SDL_blendmode.h"
#include "SDL2/SDL_render.h" #include "SDL2/SDL_render.h"
#include "SDL2/SDL_surface.h" #include "SDL2/SDL_surface.h"
#include "string.h" #include "SDL2/SDL_ttf.h"
#define NUM_DRAWCMDS 2048 #define NUM_DRAWCMDS 2048
@ -229,29 +230,25 @@ void exec_sliced_cmd(const drawcmd_t* cmd) {
} }
void exec_text_cmd(const drawcmd_t* cmd) { void exec_text_cmd(const drawcmd_t* cmd) {
SDL_FRect r = get_dest_with_size(cmd->text.area, cmd->ui); SDL_FRect r = cmd->text.area;
int fh = TTF_FontHeight(cmd->text.style.font);
float scale = 1.0 / (float)TTF_FontHeight(cmd->text.style.font) * cmd->text.style.size; int wrap = (int)(fh * r.w / cmd->text.style.size);
int pt_width = r.w * scale; SDL_Surface* s = TTF_RenderText_Solid_Wrapped(cmd->text.style.font, cmd->text.text, cmd->text.fg, wrap);
printf("scale %f ptwidth %d\n", scale, pt_width);
SDL_Surface* s = TTF_RenderText_Solid_Wrapped(cmd->text.style.font, cmd->text.text, cmd->text.fg, pt_width);
if(s != NULL) { if(s != NULL) {
SDL_Rect srcr = {0,0,s->w, s->h};
SDL_Texture* t = SDL_CreateTextureFromSurface(g_context.renderer, s); SDL_Texture* t = SDL_CreateTextureFromSurface(g_context.renderer, s);
SDL_FreeSurface(s); SDL_FreeSurface(s);
float ratio = (float)s->w / (float)pt_width; float asp_dst = r.w / r.h;
r.w *= ratio; float asp_src = (float)srcr.w / (float)srcr.h;
r.h *= ratio; if(asp_src < asp_dst) {
printf("r.w %f\n", r.w); srcr.h = srcr.w * asp_dst;
float ar = r.w / r.h;
float ar2 = (float)s->w / (float)s->h;
SDL_Rect srcr = {0, 0, s->w, s->h};
if(ar > ar2) {
srcr.h = srcr.w / ar;
} else if(ar < ar2) {
r.h = r.w / ar2;
} }
r.w = (float)srcr.w / fh * cmd->text.style.size;
r.h = (float)srcr.h / fh * cmd->text.style.size;
r = get_dest_with_size(r, cmd->ui);
SDL_RenderCopyF(g_context.renderer, t, &srcr, &r); SDL_RenderCopyF(g_context.renderer, t, &srcr, &r);
SDL_DestroyTexture(t); SDL_DestroyTexture(t);
} }