From 4700d22680347992f7c0a87715d162658eb6e4ef Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Tue, 29 Apr 2025 14:51:55 -0400 Subject: preserve image aspect ratio --- main.c | 37 ++++++++++++++++++++++++++++--------- renderer.c | 10 ++++++++++ renderer.h | 1 + 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/main.c b/main.c index 1edaeda..93673c3 100644 --- a/main.c +++ b/main.c @@ -74,6 +74,7 @@ static void mass_flow_rate_row(mu_Context *ctx, UI *ui); static void mass_flow_rate_corrected_row(mu_Context *ctx, UI *ui); static void comp_select(mu_Context *ctx, UI *ui); static void comp_img(mu_Context *ctx, UI *ui); +static void scale_preserve_aspect_ratio(mu_Rect *r, int wmax, int hmax); static void output_row(mu_Context *ctx, UI *ui, const char *label, w_Select *unit, w_Number outputs[]); static void hpad(mu_Context *ctx, int w); static void vpad(mu_Context *ctx, int h); @@ -396,20 +397,38 @@ comp_select(mu_Context *ctx, UI *ui) { static void comp_img(mu_Context *ctx, UI *ui) { - int w, h; - mu_Rect r; + mu_Rect win, area, img; - /* Row that covers the rest of the window. */ - r_get_window_size(&w, &h); - mu_layout_row(ctx, 1, &w, h); - r = mu_layout_next(ctx); - r.w = w - r.x - ctx->style->spacing; - r.h = h - r.y - ctx->style->spacing; - mu_layout_set_next(ctx, r, 0); + win.x = win.y = 0; + r_get_window_size(&win.w, &win.h); + mu_layout_row(ctx, 1, &win.w, win.h); + + area = mu_layout_next(ctx); + area.w = win.w - area.x - ctx->style->padding; + area.h = win.h - area.y - ctx->style->padding; + + img.x = area.x; + img.y = area.y; + r_get_icon_size(ui->comp_img.id, &img.w, &img.h); + + scale_preserve_aspect_ratio(&img, area.w, area.h); + + mu_layout_set_next(ctx, img, 0); w_image(ctx, &ui->comp_img); } +static void +scale_preserve_aspect_ratio(mu_Rect *r, int wmax, int hmax) { + double wscale, hscale, scale; + + wscale = (double) wmax / (double) r->w; + hscale = (double) hmax / (double) r->h; + scale = mu_min(wscale, hscale); + r->w *= scale; + r->h *= scale; +} + static void output_row(mu_Context *ctx, UI *ui, const char *label, w_Select *unit, w_Number outputs[]) { int i; diff --git a/renderer.c b/renderer.c index 900a6c9..6c5782f 100644 --- a/renderer.c +++ b/renderer.c @@ -337,3 +337,13 @@ r_remove_icon(int id) { icon_list.idx--; } + +void +r_get_icon_size(int id, int *w, int *h) { + expect(id >= 0 && id < icon_list.idx); + + *w = *h = 0; + if (SDL_QueryTexture(icon_list.items[id], NULL, NULL, w, h) != 0) { + fprintf(stderr, "%s\n", SDL_GetError()); + } +} diff --git a/renderer.h b/renderer.h index 0a31578..2a8d344 100644 --- a/renderer.h +++ b/renderer.h @@ -5,3 +5,4 @@ void r_render(mu_Context *ctx); void r_get_window_size(int *w, int *h); int r_add_icon(const char *path); void r_remove_icon(int); +void r_get_icon_size(int id, int *w, int *h); -- cgit v1.2.3