Scaling image according to screen width or height

Description

I’m developing an application that should support multiple display sizes.

What MCU/Processor/Board and compiler are you using?

lv_platformio with SDL on Linux.

What LVGL version are you using?

9.1

What do you want to achieve?

I want to have images that don’t depend on the display size. Therefore, I want to scale images to a percentage of the image width or height.

What have you tried so far?

I have developed these two functions and they work fine:

void hor_scale_image(lv_obj_t *img_obj, uint8_t width_percent) {
    // Scale image to percentage of screen width
    // Get the screen width
    int32_t screen_width = lv_disp_get_hor_res(NULL);
    // Get the original image witdh and height
    lv_img_dsc_t *img_dsc = (lv_img_dsc_t *)lv_img_get_src(img_obj);
    int32_t img_width = img_dsc->header.w;
    int32_t img_height = img_dsc->header.h;

    // Calculate target width and height based on the percentage, keeping the aspect ratio
    int32_t target_width = (screen_width * width_percent) / 100;
    int32_t target_height = (img_height * target_width) / img_width;

    // Set the size of the image object
    lv_obj_set_size(img_obj, target_width, target_height);
    lv_image_set_inner_align(img_obj, LV_IMAGE_ALIGN_STRETCH);
}

void ver_scale_image(lv_obj_t *img_obj, uint8_t height_percent) {
    // Scale image to percentage of screen height
    // Get the screen height
    int32_t screen_height = lv_disp_get_ver_res(NULL);
    // Get the original image witdh and height
    lv_img_dsc_t *img_dsc = (lv_img_dsc_t *)lv_img_get_src(img_obj);
    int32_t img_width = img_dsc->header.w;
    int32_t img_height = img_dsc->header.h;

    // Calculate target width and height based on the percentage, keeping the aspect ratio
    int32_t target_height = (screen_height * height_percent) / 100;
    int32_t target_width = img_width * target_height / img_height;

    // Set the size of the image object
    lv_obj_set_size(img_obj, target_width, target_height);
    lv_image_set_inner_align(img_obj, LV_IMAGE_ALIGN_STRETCH);
}

My question

This looks like a pretty generic need. Are there easier ways to do this with LVGL?
Thanks in advance

Hello,

You probably could have just used lv_image_set_scale_x and lv_image_set_scale_y depending on the size of your display. You will still need to calculate by how many % you want to scale it based on your display though. Might also be able to use lv_image_set_scale for fractional scaling. See the documentation: Image (lv_image) — LVGL documentation

I have not tried image scaling myself before but if the documentation is to be believed, this should work fine.