How to make switch knob smaller than the background

Description

I want to design a switch with a small padding between the knob (the white circle) and the container.

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

SDL Simulator

What LVGL version are you using?

branch release/v7

What have you tried so far?

I’ve tried setting various parts of the style (mainly padding and margin), but to no avail. This is from my last attempt:

   lv_obj_t *sw = lv_switch_create(lv_scr_act(), NULL);
    lv_obj_set_style_local_bg_color(sw, LV_SWITCH_PART_BG, LV_STATE_DEFAULT, LV_COLOR_GREEN);
    lv_obj_set_style_local_bg_color(sw, LV_SWITCH_PART_INDIC, LV_STATE_DEFAULT, LV_COLOR_GREEN);
    lv_obj_set_style_local_pad_bottom(sw, LV_SWITCH_PART_BG, LV_STATE_DEFAULT, 10);
    lv_obj_set_style_local_pad_top(sw, LV_SWITCH_PART_BG, LV_STATE_DEFAULT, 10);
    lv_obj_set_style_local_pad_bottom(sw, LV_SWITCH_PART_INDIC, LV_STATE_DEFAULT, 10);
    lv_obj_set_style_local_pad_top(sw, LV_SWITCH_PART_INDIC, LV_STATE_DEFAULT, 10);
    lv_obj_set_style_local_margin_top(sw, LV_SWITCH_PART_KNOB, LV_STATE_DEFAULT, 10);
    lv_obj_set_style_local_margin_bottom(sw, LV_SWITCH_PART_KNOB, LV_STATE_DEFAULT, 10);
    lv_obj_set_style_local_bg_color(sw, LV_SWITCH_PART_KNOB, LV_STATE_DEFAULT, LV_COLOR_WHITE);

Screenshot and/or video

This is the result I’d like to reproduce:

2020-10-12-145907_866x538_scrot

And this is what I’m stuck with:

2020-10-12-150008_480x320_scrot

Hi,

You need to apply negative padding on the knob:


  lv_obj_t *sw = lv_switch_create(lv_scr_act(), NULL);
     lv_obj_set_style_local_bg_color(sw, LV_SWITCH_PART_BG, LV_STATE_DEFAULT, LV_COLOR_GREEN);
     lv_obj_set_style_local_bg_color(sw, LV_SWITCH_PART_INDIC, LV_STATE_DEFAULT, LV_COLOR_GREEN;
     lv_obj_set_style_local_bg_color(sw, LV_SWITCH_PART_KNOB, LV_STATE_DEFAULT, LV_COLOR_WHITE);
     lv_obj_set_style_local_pad_all(sw, LV_SWITCH_PART_KNOB, LV_STATE_DEFAULT, -3);

Thank you, that worked! Previously I had resorted to a green outline to fix it, but there was still the smallest black border around the knob.

Just out of curiosity, shouldn’t a positive margin do the same job of a negative padding?

No, the margin is used by layouts to keep some extra space around the object.