Labs / LVGL

02 LVGL Basic Knowledge and Concepts

Author: Li Zisheng · Source: FreakStudio open documentation, v1.0 · License: CC BY 4.0

Contents

I. Core Objects and Interface Layout: The Skeleton System of GUI

An Object is a unified abstraction of all UI elements in LVGL and serves as the fundamental building block for constructing GUIs; together with the mechanisms of layout, scrolling and layers, it collectively defines the structure and spatial relationships of the interface.

1.1 Object Foundation (Objects)

4 0 1 2 3

1.1.1 Core Definition of an Object

All UI elements in LVGL (such as Button, Label, Image, Slider, Chart) are referred to as Objects, and are also commonly translated as "Widgets".

1.1.2 Attributes of the Object: Basic + Exclusive

The attributes of an object are divided into "basic attributes shared by all objects" and "exclusive attributes of specific controls", which correspond to two distinct sets of API designs.

1.1.2.1 Basic Attributes
Core Basic PropertiesDescription
PositionObject coordinates within the parent container (relative position)
SizeObject width and height
ParentParent object (container)
StylesStyle (visual appearance)
Event handlersEvent handler (interaction response)
1.1.2.2 Exclusive Attributes

Different types of controls have their own specific attributes, for example:

1.1.3 Working Mechanism of Objects

1.1.3.1 Parent-Child Structure

The core rules are as follows:

The core features are as follows:

1.1.3.2 Creation and Destruction of Objects

LVGL supports dynamically creating and deleting objects at runtime, and only "currently existing objects" occupy RAM, which is a core design for memory saving on embedded devices.

1.1.4 Screens: Special Top-Level Objects

A screen is a top-level object with no parent object. Each display always has an "active screen", which serves as the ultimate container for all UI elements.

We can create, activate and load, and bring up animated loading screens.

1.1.5 Parts: The "stylable components" of an object

Parts are "sub-modules" split by LVGL for widgets, similar to "pseudo-elements" in CSS, designed to enable fine-grained customization of the visual style of widgets.

LVGL has the following built-in general widgets (all controls are built by combining these components):

Part EnumerationPurposeExample scenario
LV_PART_MAINMain body of the widget (background rectangle)Button background, slider base
LV_PART_SCROLLBARScrollbarScrollbar of a list or text box
LV_PART_INDICATORIndicatorSlider progress bar, switch toggle block, checkbox tick box
LV_PART_KNOBDraggable handleSlider knob, volume control handle
LV_PART_SELECTEDSelected state markerSelected list item, selected option in a dropdown
LV_PART_ITEMSRepeated child elementsTable cells, list items
LV_PART_CURSORCursor / markerText box input cursor, chart value cursor

Different styles can be set for different parts of a control via components, for example:

1.1.6 States: The "interaction state identifier" of an object

An object can be in multiple "states" at the same time. LVGL automatically switches states based on user interactions, and also supports manual state modification. States serve as the core basis for style switching in different interaction scenarios.

The predefined states are as follows:

State EnumerationMeaningTrigger Scenarios
LV_STATE_DEFAULTDefault stateInitial state when the widget has not been operated
LV_STATE_CHECKEDChecked / toggled stateSwitch turned on, checkbox checked
LV_STATE_FOCUSEDFocused stateSelected by keyboard / encoder, touched / clicked by mouse
LV_STATE_PRESSEDPressed stateTouch / mouse is held on the widget without release
LV_STATE_DISABLEDDisabled stateWidget is not interactive (grayed out)
LV_STATE_SCROLLEDScrolled stateList / text box is being scrolled
LV_STATE_USER_1~4Custom stateBusiness extension (such as "Favorited", "Expired")

LVGL automatically updates its status based on user operations, for example:

We can also manually set / clear states via code (supports bitwise OR of multiple states |).

1.1.7 Snapshot: The "Screenshot Function" of Objects

It can generate a snapshot image (e. g. PNG/BMP) containing the object and all its sub-objects, which is commonly used for:

1.2 Layout and Space Management

The positioning, sizing and layout design of LVGL draw heavily on the core logic of CSS (with lightweight adaptations for embedded scenarios), and serve as the core capability for controlling the arrangement of UI elements.

1.2.1 Core Overview

The position/size/layout system of LVGL has the following core features (a CSS subset adapted to embedded resource constraints):

1.2.2 Core Units

LVGL supports three units, which are the basis for setting positions and dimensions, and can be passed directly in mpy via the corresponding method:

Unit TypeDescriptionExample (mpy)
PixelAbsolute pixel value; an integer represents pixels by defaultobj.set_x(10) → set the object's x coordinate to 10 pixels
PercentageRelative value (based on the parent object's content area size); requires conversion with lv.pct()obj.set_width(lv.pct(50)) → width is 50% of the parent object's content area
Content-adaptive (LV_SIZE_CONTENT)Special constant; the object size automatically fits all child elements (similar to CSS auto)obj.set_width(lv.SIZE_CONTENT) → width adapts to child elements

1.2.3 Boxing Model

LVGL follows the CSS border-box model, where an object's "size box" consists of 4 components (which determine the calculation logic for position and size):

ComponentPurposeEffect on Size
MarginBlank area outside the object (recognized only by some layouts)Does not affect the object's own size; only affects spacing to other objects
Border (border width)Border width of the objectIncluded in the object's width and height (core of border-box)
PaddingBlank space between the object's border and its child elementsIncluded in the object's width and height; child element coordinates start after the padding
Content areaActual content area of the objectContent area width/height = object width/height - left and right borders - left and right padding (same for height)

The key rules are as follows:

1.2.4 Important Notes

1.2.5 Location Settings

1.2.5.1 Location Settings

In mpy, settings can be configured directly via a simplified API, with the coordinate origin set at the top-left corner of the parent object's content area.

1.2.5.2 Alignment

Flexible alignment is achieved by modifying the "alignment origin", the core of which lies in the lv.ALIGN_XXX enumeration, which can be used directly in mpy.

We can align it to the parent object:

Core Enumeration (mpy)Meaning
lv.ALIGN.TOP_LEFTTop-left corner of the parent object
lv.ALIGN.TOP_MIDTop center of the parent object
lv.ALIGN.TOP_RIGHTTop-right corner of the parent object
lv.ALIGN.BOTTOM_LEFTBottom-left corner of the parent object
lv.ALIGN.BOTTOM_MIDBottom center of the parent object
lv.ALIGN.BOTTOM_RIGHTBottom-right corner of the parent object
lv.ALIGN.LEFT_MIDLeft center of the parent object
lv.ALIGN.RIGHT_MIDRight center of the parent object
lv.ALIGN.CENTERExact center of the parent object

You can also align it to any reference object:

Implemented via align_to, which supports the "external alignment" enumeration (LV_ALIGN_OUT_XXX). mpy example:

# Align the label to the top center of btn, offset upward by 10 pixels
label.align_to(btn, lv.ALIGN_OUT_TOP_MID, 0, -10)

External Alignment Core Enumeration (mpy):

1.2.6 Dimension Setting

1.2.6.1 Location Settings

In mpy, by simplifying API settings, it supports pixels, percentages, and LV_SIZE_CONTENT:

# Set width/height separately
obj.set_width(200)  # Width 200 pixels
obj.set_height(100) # Height 100 pixels

# Set width and height at once
obj.set_size(200, 100)

# Percentage example: height is 100% of the parent's content area (fills the parent's height)
obj.set_height(lv.pct(100))

# Content-adaptive example: width fits all child elements
obj.set_width(lv.SIZE_CONTENT)
1.2.6.2 Content Area Dimensions

Directly set the width and height of the "content area"(the actual width and height of the element = width and height of the content area + border + padding):

# Set content area width to 50 pixels (actual width = left padding + 50 + right padding)
obj.set_content_width(50)
# Set content area height to 30 pixels
obj.set_content_height(30)

# Get size (mpy)
w = obj.get_width()          # Get bounding box width
content_w = obj.get_content_width()  # Get content area width
1.2.6.3 Minimum / Maximum Dimensions

Set size extremities via style configuration to solve the issue of "percentage / Self-Adaptation size exceeding expectations", an mpy example is as follows:

# 1. Create a style and set max-height
style = lv.style_t()
style.init()
style.set_max_height(200)  # Maximum height 200 pixels (lv.pct(50) is also supported)

# 2. Add the style to the object to limit its height
obj.set_height(lv.pct(100))  # Originally fills the parent's height
obj.add_style(style, lv.PART_MAIN)  # Limit height to no more than 200 pixels

1.2.7 Style Control Position / Size

The simplified API for position and dimensions is essentially "syntactic sugar for styling", and directly using style settings offers the following advantages:

mpy example (the width increases when the button is pressed):


# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)

# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100)  # Default width 100 pixels

# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120)  # Width 120 pixels when pressed

# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)

lv.screen_load(scr)
02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts

1.2.8 Translation

Relative offset based on the object's current position, which solves the problem that "objects with different initial positions offset by the same distance during interaction"(e. g., moving up when a button is pressed), mpy example:


# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)

# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100)  # Default width 100 pixels

# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120)  # Width 120 pixels when pressed
# Create the pressed state style, set y-axis translation to -20 pixels (move up 20)
style_pressed.set_translate_y(-20)

# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)

lv.screen_load(scr)
02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts

In addition, there are two key features:

1.2.9 Transformation

"Visual scaling" based on the object's current size only changes the display effect, without affecting the actual size (the layout, scroll bars, and content Self-Adaptation will not perceive it). mpy example (enlarge when the button is pressed):


# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)

# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100)  # Default width 100 pixels

# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120)  # Width 120 pixels when pressed
# Expand width/height outward by 10 pixels each (visually +20 in width, +20 in height)
style_pressed.set_transform_width(10)
style_pressed.set_transform_height(10)

# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)

lv.screen_load(scr)
02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts
FeatureTranslationTransformation
Position / sizeChanges the real positionVisual scaling only; the real size is unchanged
Layout ImpactAffects layout / scrollbarDoes not affect layout / scrollbar
PurposePosition offset during interactionVisual scaling during interaction (no layout interference)

1.2.10 Layout System (Layout)

The layout automatically calculates the position and size of child objects (overriding manually set x/y/width/height), which is enabled via set_layout in mpy:

# Enable Flex layout on the parent container
container = lv.obj(lv.screen_active())
container.set_layout(lv.LAYOUT_FLEX)
1.2.10.1 Built-in Layouts

LVGL has two built-in core layouts (inspired by CSS), which are the most commonly used layout methods in mpy:

Layout TypeMain PurposeKey Features
Flexbox (lv.LAYOUT_FLEX)Arranges child objects in rows / columnsSupports wrapping, adaptive expansion, alignment, and spacing adjustment
Grid (lv.LAYOUT_GRID)Arranges child objects in a two-dimensional gridFixed rows and columns, cell merging, adaptive proportions

Control the behavior of child objects in the layout via flags, which in mpy are set using add_flag / remove_flag as follows:

Flags (mpy)Purpose
lv.OBJ_FLAG_HIDDENHidden objects are ignored by the layout
lv.OBJ_FLAG_IGNORE_LAYOUTThe object is completely free of layout control (position / size set manually)
lv.OBJ_FLAG_FLOATINGEquivalent to IGNORE_LAYOUT, and is ignored by LV_SIZE_CONTENT

mpy Example:

# Child object ignores the layout; position is set manually
obj.add_flag(lv.OBJ_FLAG_IGNORE_LAYOUT)
obj.set_pos(10, 10)  # Layout will not modify this position
1.2.10.3 Custom Layout

In MPY, custom layouts (for advanced use cases) can be implemented by registering layout callbacks, with the core logic as follows:

1.2.11 Scroll

The scrolling system of LVGL is the core mechanism for implementing interactive browsing when content exceeds the container in embedded GUIs, featuring an intuitive design that aligns with user expectations and supporting a rich set of customization features.

1.2.11.1 Core Principle of Scrolling

The trigger logic of scrolling in LVGL is extremely intuitive:

1.2.11.2 Scrollbar: A Visual Indicator for Scrolling

A scrollbar provides intuitive feedback of the scrolling status, and supports flexible display and style control:

1.2.11.3 Scroll Events: Monitor Scrolling Behavior

LVGL provides three types of core events for capturing the entire lifecycle of scrolling:

Core Event

Meaning of Core Events

LV_EVENT_SCROLL_BEGIN

Triggered when scrolling starts, the parameters of the scrolling animation (such as animation duration and easing curve) can be modified;

LV_EVENT_SCROLL_END

Triggered when scrolling ends, which is suitable for executing the final logic after scrolling (such as loading more content and updating status);

LV_EVENT_SCROLL

Triggered during scrolling (on every position change), suitable for real-time monitoring of scroll position (e. g., dynamically updating UI elements, recording scroll offset).

1.2.11.4 Rolling Core Expansion Features

LVGL provides a rich set of scroll enhancement features covering both interactive experience and functional control:

Feature NameCore descriptionKey controls (flag / event / API)Additional notes
Scrollability control1. Removing the specified flag disables container scrolling (scroll actions can still be passed to the parent container);
2. Can restrict the container to scroll only in specific directions (/ direction combinations)
1. Disable scrolling: remove LV_OBJ_FLAG_SCROLLABLE;
2. Direction restriction: lv_obj_set_scroll_dir(obj, LV_DIR_...)
Supported directions: LV_DIR_TOP/LEFT/BOTTOM/RIGHT/HOR/VER/ALL, can be combined (e.g. `LV_DIR_TOP、LV_DIR_LEFT`)
Scroll chainWhen a child container reaches its scroll limit, the scroll action is passed up level by level to the parent container (child → parent → grandparent), and the parent scrolls insteadEnable / disable: LV_OBJ_FLAG_SCROLL_CHAIN_HOR (horizontal) / VER (vertical)With the flag off, the scroll action ends at the current container and is no longer passed up
Scroll momentumSimulates physical inertia: after the user releases a swipe, scrolling decelerates slowly, restoring a realistic interaction feelEnable / disable: LV_OBJ_FLAG_SCROLL_MOMENTUM-
Elastic scrollWhen scrolling past the boundary, the content slightly exceeds the edge, then automatically bounces back to a valid position after release, improving the interaction experienceEnable: LV_OBJ_FLAG_SCROLL_ELASTICUnder normal conditions the container cannot scroll beyond its content
SnappingWhen scrolling ends, child objects automatically align to a specified position in the container, making scrolling more orderly (e.g. carousel / list item alignment)1. Child object can snap: LV_OBJ_FLAG_SNAPPABLE;
2. Alignment rule: lv_obj_set_scroll_snap_x/y(obj, LV_SCROLL_SNAP_...) (NONE/START/END/CENTER)
After the scroll is released, the momentum end point is calculated first, then the nearest snap point is found and scrolled to with animation
Scroll oneWhen enabled, each scroll switches only one snappable child object (e.g. a carousel moves one page per swipe)Enable: LV_OBJ_FLAG_SCROLL_ONEPrerequisite: the child objects are snappable, and the container's snap alignment is set to something other than NONE
Scroll on focusWhen focus moves to a child object outside the container's visible area, the container automatically scrolls to bring that object into viewNo specific control flag; a built-in LVGL featureSupports recursive scroll adaptation for nested containers and across tabs (tabview)
Manual scrolling1. Active trigger: scroll by an offset / to specified coordinates;
2. Real-time retrieval: scroll offset coordinates
1. Trigger API: lv_obj_scroll_by/to/to_x/to_y();
2. Coordinate retrieval API: lv_obj_get_scroll_x/y/top/bottom/left/right()
Can be used for saving the scroll position, updating the UI dynamically, etc.
Self size1. Self size is the actual size of the object's content area (as opposed to its displayed size);
2. Scrolling is triggered when self size > displayed size (scrolling is possible even without children)
Custom self size: handle the LV_EVENT_GET_SELF_SIZE eventTypical scenario: table widget (many rows make the self height much larger than the displayed height)

1.3 Layer Management (Layers)

The layers in LVGL essentially control the rendering hierarchy of UI elements (i. e., "which element appears on top of another"), and there are two core hierarchical systems:

To be precise:

1 1.3

1.3.1 Creation Order: Default Hierarchy Rules

LVGL follows the default "later-created objects on top" principle: newly created objects (and their child objects) are drawn on top of older objects (and their child objects), which may cover the display area of the older objects.

# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

# Create the first button (created first, lower in z-order)
btn1 = lv.button(scr)
# Position (x=60, y=40)
btn1.set_pos(60, 40)      
label1 = lv.label(btn1)
label1.set_text("Button 1")

# Create the second button (created later, higher in z-order, covers the overlapping area of btn1)
btn2 = lv.button(scr)
# Position (x=60, y=60)
btn2.set_pos(60, 60)     
label2 = lv.label(btn2)
label2.set_text("Button 2")

lv.screen_load(scr)
1 2

1.3.2 Modify Hierarchy: Proactively Adjust the Display Order of Objects

When the default creation order fails to meet requirements (e. g., moving a low-level button to the top layer), LVGL provides 4 explicit methods to modify the layer order, which can be directly invoked via the corresponding object methods in MicroPython:

1.3.2.1 Pin to Top / Pin to Bottom (Most Commonly Used)
Method (mpy)Purpose
obj.move_foreground()Move the object (and its children) to the top layer of the parent container
obj.move_background()Move the object (and its children) to the bottom layer of the parent container
1 2 btn1.move_foreground btn1

mpy example: Bring the previously created btn1 to the top layer (to cover btn2)

# Move btn1 to the topmost layer of the parent container (scr)
btn1.move_foreground()
1.3.2.2 Move to the specified index position

Each child object of a parent container has an "index value", which determines the hierarchy:

mpy core method:

# 1. Get the object's current index
current_idx = obj.get_index()

# 2. Move to the specified index (e.g., move up 1 level)
obj.move_to_index(current_idx + 1)

# 3. Move directly to the bottom layer (index 0)
obj.move_to_index(0)

mpy example:

1 btn1.move_foreground btn1.get_index
1 2
1 2 btn1 0
1.3.2.3 Hierarchy Impact of Changing the Parent Object

When you modify the parent container of an object via obj.set_parent (new_parent), the object will automatically become the topmost child object of the new parent container.

# Change btn1's parent to btn2; btn1 becomes the topmost child of btn2
btn1.set_parent(btn2)
2 1 btn1.set_parent btn2

1.3.3 Top Layer and System Layer (Top & Sys Layers)

LVGL provides two globally visible special layers (shared by all screens, not shared across different displays) for each physical display, which are hierarchically higher than all objects on ordinary screens:

Many beginners are confused about LVGL's layer_top / layer_sys / layer_bottom, and the core reason is that they fail to understand the essential difference between "ordinary screen objects" and "global special layers":

显示器最终显示效果 = 最顶层往下叠加
├─ layer_sys(系统层,最顶层)→ 比如鼠标光标,永远在所有内容上面
├─ layer_top(顶级图层)→ 比如全局弹窗、悬浮窗,覆盖所有屏幕
├─ 当前活跃的普通屏幕(屏幕A/屏幕B)→ 普通按钮/标签都在这一层
└─ layer_bottom(底层图层)→ 比如全局背景图,在所有屏幕下面
1.3.3.1 layer_top (Top-level Layer): Globally Visible "Floating Window / Modal Pop-up"

Similar to the "floating window" or "system pop-up window" on a mobile phone: no matter which APP (corresponding to a regular screen in LVGL) you switch to, the floating window remains displayed; when "modal mode" is enabled, the underlying content cannot be clicked (for example, a mobile phone pop-up window blocks operations on the APP).

In the following code, two regular screens that can be switched between each other are created, and a globally visible modal popup is generated on layer_top. This popup is similar to the "system-level popup" on mobile phones: it does not disappear when switching between screens, and will block the interaction of the underlying screen. The underlying buttons can only be used normally after the popup is closed.

# Initialize

import display_driver
import lvgl as lv

lv.init()

# ===================== Step 1: Create two normal screens (for switching test) =====================
# Screen A: add a button; clicking it switches to screen B
scr_a = lv.obj()  # Create normal screen A
btn_a = lv.button(scr_a)
btn_a.set_size(180, 60)
btn_a.set_pos(50, 50)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")

# Screen B: add a button; clicking it switches to screen A
scr_b = lv.obj()  # Create normal screen B
btn_b = lv.button(scr_b)
btn_b.set_size(180, 60)
btn_b.set_pos(50, 150)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")

# Bind the screen switching event
def switch_to_b(e):
    lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)

def switch_to_a(e):
    lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)

# ===================== Step 2: Create a global modal popup with layer_top =====================
# 1. Get the display's top layer (global layer, shared by all screens)
top_layer = lv.layer_top()

# 2. Add a "click absorb" flag to top_layer → implements modal behavior (buttons below cannot be clicked)
# Principle: when the user clicks the screen, the click event is received by top_layer, and widgets on the underlying screen do not get the click event
top_layer.add_flag(lv.obj.FLAG.CLICKABLE)

# 3. Create the popup on top_layer (globally visible, stays regardless of which screen is shown)
popup = lv.obj(top_layer)  # The parent object is top_layer, not a normal screen!
popup.set_size(300, 200)   # Popup size
popup.center()             # Popup centered
# Set popup style: white background, gray border, rounded corners
popup.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)    # White background
popup.set_style_border_color(lv.color_hex(0xCCCCCC), 0)# Gray border
popup.set_style_border_width(2, 0)                     # Border width 2px
popup.set_style_radius(10, 0)                          # Corner radius 10px

# 4. Add text + close button to the popup
popup_label = lv.label(popup)
popup_label.set_text("Global Modal Popup\n→ Persists across screen switches\n→ Blocks clicks on underlying elements")
popup_label.center()

# Add close button: clicking it removes the modal and closes the popup
close_btn = lv.button(popup)
close_btn.set_size(120, 30)
close_btn.align(lv.ALIGN.BOTTOM_MID, 0, -10)  # Popup bottom center
close_label = lv.label(close_btn)
close_label.set_text("Close Popup")

# Event to close the popup: remove click absorption + delete the popup
def close_popup(e):
    top_layer.remove_flag(lv.obj.FLAG.CLICKABLE)  # Cancel click absorption
    popup.delete()  # Delete the popup
close_btn.add_event_cb(close_popup, lv.EVENT.CLICKED, None)

# ===================== Step 3: Load the initial screen and run the test =====================
lv.screen_load(scr_a)  # Load screen A first
02 LVGL Basic Knowledge and Concepts

It can be seen that:

02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts
1.3.3.2 layer_sys (system layer): the topmost "system-level element"

LVGL internally uses this layer to place elements that "must always be on top"(such as the mouse cursor). Even if layer_top has a pop-up window, layer_sys content will still cover the pop-up.

The demo code is as follows:

# Initialize

import display_driver
import lvgl as lv
import time

lv.init()

# ===================== Step 1: Create two normal screens (for switching test) =====================
# Screen A: add a button; clicking it switches to screen B
scr_a = lv.obj()  # Create normal screen A
btn_a = lv.button(scr_a)
btn_a.set_size(180, 60)
btn_a.set_pos(50, 50)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")

# Screen B: add a button; clicking it switches to screen A
scr_b = lv.obj()  # Create normal screen B
btn_b = lv.button(scr_b)
btn_b.set_size(180, 60)
btn_b.set_pos(50, 150)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")

# Bind the screen switching event
def switch_to_b(e):
    lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)

def switch_to_a(e):
    lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)

# ===================== Step 2: Create a global modal popup with layer_top =====================
# 1. Get the display's top layer (global layer, shared by all screens)
top_layer = lv.layer_top()

# 2. Add a "click absorb" flag to top_layer → implements modal behavior (buttons below cannot be clicked)
# Principle: when the user clicks the screen, the click event is received by top_layer, and widgets on the underlying screen do not get the click event
top_layer.add_flag(lv.obj.FLAG.CLICKABLE)

# 3. Create the popup on top_layer (globally visible, stays regardless of which screen is shown)
popup = lv.obj(top_layer)  # The parent object is top_layer, not a normal screen!
popup.set_size(300, 200)   # Popup size
popup.center()             # Popup centered
# Set popup style: white background, gray border, rounded corners
popup.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)    # White background
popup.set_style_border_color(lv.color_hex(0xCCCCCC), 0)# Gray border
popup.set_style_border_width(2, 0)                     # Border width 2px
popup.set_style_radius(10, 0)                          # Corner radius 10px

# 4. Add text + close button to the popup
popup_label = lv.label(popup)
popup_label.set_text("Global Modal Popup\n→ Persists across screen switches\n→ Blocks clicks on underlying elements")
popup_label.center()

# Add close button: clicking it removes the modal and closes the popup
close_btn = lv.button(popup)
close_btn.set_size(120, 30)
close_btn.align(lv.ALIGN.BOTTOM_MID, 0, -10)  # Popup bottom center
close_label = lv.label(close_btn)
close_label.set_text("Close Popup")

# Event to close the popup: remove click absorption + delete the popup
def close_popup(e):
    top_layer.remove_flag(lv.obj.FLAG.CLICKABLE)  # Cancel click absorption
    popup.delete()  # Delete the popup
close_btn.add_event_cb(close_popup, lv.EVENT.CLICKED, None)

# ===================== Step 3: Load the initial screen and run the test =====================
lv.screen_load(scr_a)  # Load screen A first

# Get the system layer (topmost layer)
sys_layer = lv.layer_sys()

# 2. Create a small circle (simulates a mouse cursor)
cursor = lv.obj(sys_layer)
cursor.set_size(20, 20)       # Cursor size 20x20
cursor.set_style_bg_color(lv.color_hex(0xFF0000), 0)  # Red background
cursor.set_style_radius(10, 0)                        # Circle (radius = size/2)
30 100

After running, you can see the following:

As we run the command to adjust the ball position in the REPL, the red circular cursor will pass through the pop-up window of layer_top and always stay on the top (it remains visible even when blocked by the pop-up window).

The summary is as follows:

1.3.3 layer_bottom (bottom layer): global background image

Set the "background for all screen sharing", such as the global background image of an APP, so that the background remains unchanged no matter which page (screen) you switch to (provided that the screen background is semi-transparent).

In the following code, we set:

# Initialize

import display_driver
import lvgl as lv
import time

lv.init()

# ===================== Step 1: Create the global background for layer_bottom =====================
# Get the bottom layer
bottom_layer = lv.layer_bottom()

# Global background: dark blue (#1A237E), fully opaque (to highlight the global background)
bg_rect = lv.obj(bottom_layer)
bg_rect.set_size(lv.pct(80), lv.pct(80))  # Fill the entire screen
bg_rect.set_style_bg_color(lv.color_hex(0x1A237E), 0)  # Dark blue (high contrast)
bg_rect.set_style_bg_opa(255, 0)  # Background opaque

# ===================== Step 2: Create two normal screens (semi-transparent background) =====================
# Screen A: semi-transparent background (so the light cyan of the bottom layer shows through)
scr_a = lv.obj()
scr_a.set_style_bg_opa(64, 0)  # Opacity 64 (25%), more transparent
scr_a.set_style_bg_color(lv.color_hex(0xF5F5F5), 0)  # Light gray
btn_a = lv.button(scr_a)
btn_a.set_pos(50, 50)
btn_a.set_size(180, 60)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")

# Screen B: semi-transparent background as well
scr_b = lv.obj()
scr_b.set_style_bg_opa(64, 0)
scr_b.set_style_bg_color(lv.color_hex(0xF5F5F5), 0)
btn_b = lv.button(scr_b)
btn_b.set_pos(50, 150)
btn_b.set_size(180, 60)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")

# Bind the switch event
def switch_to_b(e):
    lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)

def switch_to_a(e):
    lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)

# ===================== Step 3: Test the result =====================
lv.screen_load(scr_a)
02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts

It can be seen that when switching between screens A and B, the dark blue global background remains unchanged at all times, while the light gray screen background changes accordingly with the switch.

II. Visual Style and Resource System: GUI Skins and Creatives

Styles serve as the core for controlling the visual presentation of objects. Together with basic resources such as colors, fonts and images, they collectively define the visual style of a GUI, and support highly customized and thematized configurations.

First, memorize the 3 most fundamental concepts:

Official conceptPlain-language understandingExample
StyleThe widget's "appearance set"Can define an appearance such as "red background, 2px black border, white text", like dressing up a widget
StateThe widget's "behavior state"A button displayed normally (default), pressed by a finger, selected, or disabled, like a person standing / sitting / running
PartA complex widget's "components"A slider is split into: background (base), progress bar (indicator), and knob (adjustment handle); each part can be styled separately

At the same time, there are two key rules as follows:

Basic visual resources include:

2.1 Style System (Styles)

Styles in LVGL serve as the core mechanism for controlling the appearance of UI components (objects), which are designed with reference to CSS while adapted to the lightweight characteristics of embedded GUIs.

First, quickly align the core terms of LVGL styling through CSS analogy:

LVGL conceptCSS equivalent conceptPlain explanation
lv_style_tCSS class (.btn)Container that stores style properties (such as border, color, font)
Target PartCSS pseudo-element (::after)A component's parts (such as a slider's knob, a button's text area)
Target StateCSS pseudo-class (:hover)A component's state (such as pressed, focused, disabled, default)
Style cascadingCSS class stacking (.btn.red)Multiple styles are stacked, with properties overridden as needed
Style priorityCSS priority rulesLater-added styles > earlier-added ones; local styles > normal styles
InheritanceCSS inheritance (such as text color)Child components can inherit some style properties from the parent component

2.2 State

The State in LVGL refers to binary flag bits that describe the current behavior/status of an object (such as a button or slider), whose core function is to bind different styles to objects in different states or state combinations, so as to realize interactive effects such as "changing color on click, adding a border when focused". In mpy, state constants are called in the form of lv.STATE.XXX, and the corresponding relationship is as follows:

MicroPython state constantValueMeaningPriority (higher value = higher priority)
lv.STATE.DEFAULT0x0000Normal / released state (default fallback)Lowest
lv.STATE.CHECKED0x0001Checked / toggled state (e.g. a checkbox is checked)↑
lv.STATE.FOCUSED0x0002Focused state (triggered by keyboard / touch / mouse)↑
lv.STATE.FOCUS_KEY0x0004Focus triggered only by keyboard / encoder (not touch)↑
lv.STATE.EDITED0x0008Encoder edit state↑
lv.STATE.HOVERED0x0010Mouse hover (not supported yet)↑
lv.STATE.PRESSED0x0020Pressed state↑
lv.STATE.SCROLLED0x0040Scrolled state↑
lv.STATE.DISABLED0x0080Disabled state↑
lv.STATE.USER_1 ~ 40x1000+Custom state (extend as needed)Highest (user-defined)
02 LVGL Basic Knowledge and Concepts

When LVGL matches styles to objects, it follows the logic of " states with higher priority override those with lower priority, and fall back to the default if no match is found ", with the core rules as follows:

Suppose the following styles are set for the button:

Style matching results in different states:

2.3 Cascading Styles

You don't need to define all appearance attributes in a single style; you can apply multiple styles to the same object. Styles added later have higher priority (and will override the same attributes of previously added styles), however, state priority always takes precedence over cascade priority.

2.4 Style Inheritance

Some attributes (mainly text-related attributes such as font, text color, and text alignment) can be inherited from the parent object, and the parent object's style will be looked up upward only when none of the child object's own styles (including the default state) have set this attribute.

The parent object uses its current state to provide inherited values. For example, when a button is in the "pressed" state, if the text label inside the button has no text color configured, it will inherit the text color of the button's "pressed" state instead of the default state.

2.5 Parts

LVGL widgets consist of multiple "functional components", each of which can be styled independently (similar to CSS pseudo-elements such as:: after), enabling differentiated appearances for different areas of the widget.

Predefined Core Components (General):

Predefined Core Component Names

Meaning

LV_PART_MAIN

Control body (e. g., the background of a button, the overall background of a slider)

LV_PART_INDICATOR

Indicators (such as the Progress Bar of a slider, the on indicator of a switch, and the check box of a checkbox)

LV_PART_KNOB

Adjustment handle / (e. g. the draggable button of a slider, the adjustment point of a scroll wheel)

LV_PART_SCROLLBAR

scroll bar

LV_PART_SELECTED

Selected item (e. g. the selected entry in a drop-down box)

LV_PART_CURSOR

Cursor (e. g., the input cursor in a text box)

Example: The slider consists of three components: MAIN (background), INDICATOR (Progress Bar), and (adjustment ), and you may set the to red, the Progress Bar to blue, and the background to gray respectively.

2.6 Style Initialization and Attribute Manipulation

Essentially, a style is a variable of type lv_style_t, and all operations on it must follow fixed rules:

02 LVGL Basic Knowledge and Concepts

2.7 Add / Replace / Remove Styles for Controls

A style takes effect only when bound to a control, and the core operation revolves around the "selector"(a combination of a component and its state):

2.8 Style Change Notification

After modifying the style that has been bound to a control, you need to actively notify the control to refresh it, otherwise the style will not take effect:

02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts
02 LVGL Basic Knowledge and Concepts

2.9 Obtain the Final Style Property Value of the Control

You can obtain the final property value of a certain component of a control via get_style_<property_name>(control, component), and this function will automatically synthesize the following:

2.10 Local Styles

Analogous to inline styles in CSS (<div style="color:red">), but with more powerful features:

2.11 Transitions

When switching the default state, style properties change immediately; transitions enable animated gradients (e. g., a 300ms gradient of the background color when a button is pressed):

2.12 Opacity, Blend Mode and Transform

When setting opa (opacity), transform_angle (rotation), transform_zoom (scaling) and other properties:

2.13 Themes

A theme is a collection of styles used to unify the default appearance of the entire interface:

2.14 Summary Table of Style Attributes

2.14.1 Dimensions and Location (Size and position)

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
widthSets the object width; supports pixels / percentage / LV_SIZE_CONTENTWidget-specificNoYesNo
min_widthMinimum width limit0NoYesNo
max_widthMaximum width limitLV_COORD_MAXNoYesNo
heightSets the object height; supports pixels / percentage / LV_SIZE_CONTENTWidget-specificNoYesNo
min_heightMinimum height limit0NoYesNo
max_heightMaximum height limitLV_COORD_MAXNoYesNo
xX coordinate relative to the alignment reference0NoYesNo
yY coordinate relative to the alignment reference0NoYesNo
alignAlignment relative to the parentLV_ALIGN_DEFAULTNoYesNo
transform_widthWiden the object in both directions0NoNoYes
transform_heightHeighten the object in both directions0NoNoYes
translate_xX offset after layout0NoYesNo
translate_yY offset after layout0NoYesNo
transform_zoomZoom; 256 = original size0NoYesYes
transform_angleRotation angle (in units of 0.1°)0NoYesYes
transform_pivot_xTransform pivot X coordinate0NoNoNo
transform_pivot_yTransform pivot Y coordinate0NoNoNo

2.14.2 Padding

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
pad_topTop padding0NoYesNo
pad_bottomBottom padding0NoYesNo
pad_leftLeft padding0NoYesNo
pad_rightRight padding0NoYesNo
pad_rowLayout row spacing0NoYesNo
pad_columnLayout column spacing0NoYesNo

2.14.3 Margin

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
margin_topTop margin0NoYesNo
margin_bottomBottom margin0NoYesNo
margin_leftLeft margin0NoYesNo
margin_rightRight margin0NoYesNo

2.14.4 Background

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
bg_colorBackground color0xffffffNoNoNo
bg_opaBackground opacityLV_OPA_TRANSPNoNoNo
bg_grad_colorBackground gradient color0x000000NoNoNo
bg_grad_dirGradient directionLV_GRAD_DIR_NONENoNoNo
bg_main_stopMain color gradient start point0NoNoNo
bg_grad_stopGradient color start point255NoNoNo
bg_gradGradient descriptorNULLNoNoNo
bg_dither_modeGradient dither modeLV_DITHER_NONENoNoNo
bg_img_srcBackground image sourceNULLNoNoYes
bg_img_opaBackground image opacityLV_OPA_COVERNoNoNo
bg_img_recolorBackground image recolor color0x000000NoNoNo
bg_img_recolor_opaImage recolor intensityLV_OPA_TRANSPNoNoNo
bg_img_tiledBackground image tiling0NoNoNo

2.14.5 Border

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
border_colorBorder color0x000000NoNoNo
border_opaBorder opacityLV_OPA_COVERNoNoNo
border_widthBorder width (pixels only)0NoYesNo
border_sideBorder sides to displayLV_BORDER_SIDE_NONENoNoNo
border_postBorder drawing timing (after / before children)0NoNoNo

2.14.6 Outline

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
outline_widthOutline width0NoNoYes
outline_colorOutline color0x000000NoNoNo
outline_opaOutline opacityLV_OPA_COVERNoNoYes
outline_padOutline-to-object spacing0NoNoYes

2.14.7 Shadow

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
shadow_widthShadow width0NoNoYes
shadow_offset_xShadow X offset0NoNoYes
shadow_offset_yShadow Y offset0NoNoYes
shadow_spreadShadow spread0NoNoYes
shadow_colorShadow color0x000000NoNoNo
shadow_opaShadow opacityLV_OPA_COVERNoNoYes

2.14.8 Image

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
img_opaImage opacityLV_OPA_COVERNoNoNo
img_recolorImage recolor blend color0x000000NoNoNo
img_recolor_opaImage recolor intensity0NoNoNo

2.14.9 Line

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
line_widthLine width0NoNoYes
line_dash_widthDash width0NoNoYes
line_dash_gapDash gap0NoNoYes
line_roundedLine end rounding0NoNoYes
line_colorLine color0x000000NoNoNo
line_opaLine opacityLV_OPA_COVERNoNoNo

2.14.10 Arc

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
arc_widthArc thickness0NoNoYes
arc_roundedArc end rounding0NoNoYes
arc_colorArc color0x000000NoNoNo
arc_opaArc opacityLV_OPA_COVERNoNoNo
arc_img_srcArc mask imageNULLNoNoNo

2.14.11 Text

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
text_colorText color (hexadecimal RGB value)0x000000 (black)YesNoNo
text_opaText opacity, value range:
- 0/LV_OPA_TRANSP (fully transparent)
- 255/LV_OPA_COVER (fully opaque)
- 10~90/LV_OPA_10~LV_OPA_90 (semi-transparent)
LV_OPA_COVERYesNoNo
text_fontText font (pointer to type lv_font_t)LV_FONT_DEFAULT (default font)YesYesNo
text_letter_spaceLetter spacing (unit: pixels)0YesYesNo
text_line_spaceLine spacing for multi-line text (unit: pixels)0YesYesNo
text_decorText decoration, supports bitwise OR combination:
- LV_TEXT_DECOR_NONE (no decoration)
- LV_TEXT_DECOR_UNDERLINE (underline)
- LV_TEXT_DECOR_STRIKETHROUGH (strikethrough)
LV_TEXT_DECOR_NONEYesNoNo
text_alignText alignment within a line (affects only text lines, not the object itself):
- LV_TEXT_ALIGN_LEFT (left aligned)
- LV_TEXT_ALIGN_CENTER (center aligned)
- LV_TEXT_ALIGN_RIGHT (right aligned)
- LV_TEXT_ALIGN_AUTO (auto, adapts to the text base direction)
LV_TEXT_ALIGN_AUTOYesYesNo

2.14.12 Miscellaneous

Property nameFunction descriptionDefault valueInheritedAffects layoutExtra draw
radiusCorner radius0NoNoNo
clip_cornerClip overflow content at rounded corners0NoNoNo
opaOverall object opacity scalingLV_OPA_COVERYesNoNo
color_filter_dscColor filter descriptorNULLNoNoNo
color_filter_opaColor filter intensityLV_OPA_TRANSPNoNoNo
animAnimation templateNULLNoNoNo
anim_timeAnimation duration (ms)0NoNoNo
anim_speedAnimation speed (px/sec)0NoNoNo
transitionStyle transition descriptorNULLNoNoNo
blend_modeColor blend modeLV_BLEND_MODE_NORMALNoNoNo
layoutChild widget layout0NoYesNo
base_dirText base direction (LTR/RTL)LV_BASE_DIR_AUTOYesYesNo

2.15 Colors

2.15.1 Core Basic Knowledge

The color module of LVGL is the underlying core of UI rendering, which is responsible for color creation, format conversion, color adjustment and transparency control. The core principles of its design are as follows: Unified color interface —— No matter what the system-configured color depth (LV_COLOR_DEPTH) is, all APIs interact based on the lv_color_t type (fixed RGB888 format), and the framework automatically handles the underlying color depth conversion without requiring developers to pay extra attention.

lv_color_t is the standard type for color storage in LVGL, with the following core features:

RGB is the most commonly used color definition method for embedded UIs, and LVGL provides three convenient interfaces:

Interface formPurposeExample
lv_color_make(r,g,b)Create color dynamically (runtime)lv_color_t c = lv_color_make(255,0,0); (pure red)
LV_COLOR_MAKE(r,g,b)Constant initialization (compile time)const lv_color_t c = LV_COLOR_MAKE(0,255,0); (pure green)
lv_color_hex(0xRRGGBB)6-digit hexadecimal (RR = red, GG = green, BB = blue)lv_color_t c = lv_color_hex(0x0000FF); (pure blue)
lv_color_hex3(0xRGB)3-digit shorthand hexadecimal (automatically expanded to 6 digits)lv_color_t c = lv_color_hex3(0x123); (equivalent to 0x112233)
RGB888 to_32

2.15.2 Methods for Creating Colors

2.15.1.1 RGB Mode Creation (the most basic method, directly specifying red/green/blue)

RGB is the most commonly used color definition method for embedded UIs, and LVGL provides three convenient interfaces:

Interface formPurposeExample
lv_color_make(r,g,b)Create color dynamically (runtime)lv_color_t c = lv_color_make(255,0,0); (pure red)
LV_COLOR_MAKE(r,g,b)Constant initialization (compile time)const lv_color_t c = LV_COLOR_MAKE(0,255,0); (pure green)
lv_color_hex(0xRRGGBB)6-digit hexadecimal (RR = red, GG = green, BB = blue)lv_color_t c = lv_color_hex(0x0000FF); (pure blue)
lv_color_hex3(0xRGB)3-digit shorthand hexadecimal (automatically expanded to 6 digits)lv_color_t c = lv_color_hex3(0x123); (equivalent to 0x112233)
2.15.1.2 HSV Mode Creation (Suitable for Dynamic Color Adjustment/Gradient)

HSV (Hue, Saturation, Value) better aligns with the human eye's perception of color, making it suitable for scenarios that require color gradients and dynamic hue adjustment:

Core conversion function:

2.15.1.3 Palette Creation (Material Design Preset Colors, Simplified UI Color Matching)

LVGL has a built-in Material Design color palette that provides 19 base colors, each consisting of a main color, 4 dark variants and 5 light variants, eliminating the need for manual RGB value adjustment and ensuring consistent UI colors.

How to use the palette:

2.15.3 Modification and Blending of Colors

LVGL provides convenient functions to adjust color brightness and blend two colors, meeting the needs of dynamic UIs (such as button pressed/hover states, gradient backgrounds):

Function nameFunctionParameter description
lv_color_lighten(c, lvl)Lighten colorlvl=0 (unchanged) ~ 255 (all white)
lv_color_darken(c, lvl)Darken colorlvl=0 (unchanged) ~ 255 (all black)
lv_color_change_lightness(c, lvl)Overall brightness adjustmentlvl=0 (all black), 128 (unchanged), 255 (all white)
lv_color_mix(c1, c2, ratio)Mix two colorsratio=0 (all c2), 128 (half each), 255 (all c1)

2.15.4 Transparency

LVGL uses the lv_opa_t type (based on uint8_t, with values ranging from 0 to 255) to describe transparency, which centers on the concept of "coverage": the higher the value, the less transparent the color, and the more of the underlying content it obscures.

2.15.5 Core Constants

Palette base color constants:

Constant nameCorresponding colorConstant nameCorresponding color
LV_PALETTE_REDRedLV_PALETTE_GREENGreen
LV_PALETTE_PINKPinkLV_PALETTE_LIGHT_GREENLight green
LV_PALETTE_PURPLEPurpleLV_PALETTE_LIMELime
LV_PALETTE_DEEP_PURPLEDeep purpleLV_PALETTE_YELLOWYellow
LV_PALETTE_INDIGOIndigoLV_PALETTE_AMBERAmber
LV_PALETTE_BLUEBlueLV_PALETTE_ORANGEOrange
LV_PALETTE_LIGHT_BLUELight blueLV_PALETTE_DEEP_ORANGEDeep orange
LV_PALETTE_CYANCyanLV_PALETTE_BROWNBrown
LV_PALETTE_TEALTealLV_PALETTE_BLUE_GREYBlue gray
LV_PALETTE_GREYGray--

Transparency Constants:

Constant nameValueMeaningConstant nameValueMeaning
LV_OPA_TRANSP0Fully transparentLV_OPA_6015360% opaque
LV_OPA_102510% opaque (almost transparent)LV_OPA_7017870% opaque
LV_OPA_205120% opaqueLV_OPA_8020480% opaque
LV_OPA_307630% opaqueLV_OPA_9022990% opaque (almost opaque)
LV_OPA_4010240% opaqueLV_OPA_COVER255Fully opaque (default)
LV_OPA_5012850% opaque (semi-transparent)---

2.16 Fonts and Icons

The font module of LVGL is the core of text rendering, essentially a package of "glyph bitmap set + rendering control information". All fonts are ultimately stored in the lv_font_t structure, and are bound for use via the text_font field of the widget style.

2.16.1 Core Fundamentals: Pixel Precision of Fonts (bpp)

bpp (bits per pixel, short for bits per pixel) is the most fundamental core attribute of a font, which determines the edge smoothness and memory footprint of the font:

2.16.2 Unicode and Symbol Support (Basic Text Rendering)

LVGL natively supports UTF-8 encoding Unicode characters, which serves as the foundation for multi-language and symbol rendering:

2.16.2.1 Enablement Conditions

Ensure that lv_conf.h has LV_TXT_ENC = LV_TXT_ENC_UTF8 (enabled by default), and the code files are saved in UTF-8 encoding.

2.16.2.2 Usage of Built-in Symbols

LVGL extends built-in fonts with FontAwesome icons (such as check marks, WiFi symbols, play buttons, etc.), which can be used directly via the LV_SYMBOL_XXX constants:

02 LVGL Basic Knowledge and Concepts

2.16.3 Built-in Fonts

LVGL provides multiple types of built-in fonts, which need to be enabled via lv_conf.h using the LV_FONT_… macros, and are mainly divided into two categories: "ordinary fonts" and "special fonts":

2.16.3.1 Regular Font (Montserrat Family)

Based on the Montserrat font, it covers ASCII characters, the degree sign (U+ 00B0), bullet point (U+ 2022) and built-in symbols, offers 19 sizes ranging from 12px to 48px, and follows the naming convention of LV_FONT_MONTSERRAT_<size>(for example, LV_FONT_MONTSERRAT_16), which corresponds to the global variable lv_font_montserrat_16.

2.16.3.2 Special Font
Constant nameFeatureApplicable scenarios
LV_FONT_MONTSERRAT_28_COMPRESSED28px, 3bpp + compressed storageLarge screens with low memory
LV_FONT_DEJAVU_16_PERSIAN_HEBREW16px, supports Hebrew / Arabic / PersianMiddle Eastern language interfaces
LV_FONT_SIMSUN_16_CJK16px, includes 1000 common CJK charactersBasic CJK (Chinese, Japanese, Korean) interface
LV_FONT_UNSCII_8/168/16px, pixel style, ASCII onlyRetro pixel-style UI, low-memory devices

2.16.4 Special Rendering Features of Fonts

2.16.4.1 Bidirectional Text (BiDi) Support

Supports rendering for left-to-right (LTR) and right-to-left (RTL) languages (such as Arabic and Hebrew), as well as mixed-direction text:

2.16.4.2 Arabic / Persian Character Support

The character forms of such languages vary depending on their position (isolated/initial/medial/final), and LVGL enables LV_USE_ARABIC_PERSIAN_CHARS to support this rule, but there are 3 limitations:

2.16.4.3 Subpixel Rendering

By leveraging the RGB sub-pixel layout of screen pixels, the horizontal resolution is tripled, resulting in smoother font edges:

Serial No.

Function

Description

Enabling / Configuration Method

Restrictions / Precautions

1

Bidirectional Text (BiDi) Support

It supports left-to-right (LTR) and right-to-left (RTL) languages (such as Arabic and Hebrew), and also supports mixed-direction text rendering.

Enable LV_USE_BIDI in lv_conf.h; you can set the base direction for a widget via lv_obj_set_base_dir (obj, dir); common constants include LV_BASE_DIR_LTR, LV_BASE_DIR_RTL, and LV_BASE_DIR_AUTO.

In RTL mode, the control creation position, Tab bar, checkboxes and other elements will automatically adapt to the right-to-left layout.

2

Arabic / Persian character support

It supports the character forms of such languages that vary according to their position (isolated / initial / medial / final).

Enable LV_USE_ARABIC_PERSIAN_CHARS in lv_conf.h.

Only supports the display of static text such as Label, and does not support text input boxes (Text Area); only processes dynamic text (e. g., lv_label_set_text ()), and does not process static text (e. g., lv_label_set_text_static ()); the processed form will be returned when obtaining the text.

3

Subpixel Rendering

By leveraging the RGB sub-pixel layout of screen pixels, it improves the horizontal resolution to make font edges more delicate.

When generating fonts, check the "Subpixel" option (in the online converter), or add the --lcd flag in the command line; you can configure LV_SUBPX_BGR to match the subpixel order of the display screen.

Font memory increases by approximately 3x; it is necessary to match the sub-pixel order (RGB / BGR) of the screen.

4

Subset Font

Compresses font bitmaps to reduce memory usage, making it suitable for large-sized fonts.

Check the "Compressed" option in the online converter; this feature is enabled by default in the command line, and you can use --no-compress to disable it.

The rendering speed is approximately 30% slower; it is recommended to only compress large-sized, infrequently used fonts; the compression effect is more significant for large-size / high-bpp fonts.

5

Kerning

Adjust the spacing between specific character pairs (e. g., "AV", "Ta") to enhance the visual appeal of typesetting.

Generated by the online converter by default; add --no-kerning in the command line to disable it;lv_font_set_kerning () can be used at runtime.

FreeType integration is not supported for the time being; Tiny TTF supports GPOS/Kern tables.

2.16.5 Font Extension (Custom / Dynamic Loading)

Serial No.

Functions

Description

Implementation / Configuration

Restrictions / Notes

1

Add New Fonts (Core Extension Method)

LVGL does not natively support vector fonts such as TTF and WOFF, which need to be converted into bitmap fonts before use.

① Online converter: Configure dimensions, bpp, and character range, then generate a C file to add to the project; ② Offline converter (Node.js): Suitable for batch and local generation;

③ Built-in Font Script (Python): Generates Montserrat fonts with custom dimensions and character ranges.

It must be converted to a bitmap font before use; the font size increases significantly with the dimensions and character set.

2

Add New Symbol

Extend custom symbols (such as USB, battery icons) based on FontAwesome.

① Obtain the Unicode ID of the symbol;

② Import FontAwesome in the online converter and specify the corresponding Unicode; ③ Generate the font file;

④ Define and use constants after converting Unicode to UTF-8.

Ensure that the corresponding Unicode characters are included in the font, and different encoding formats are converted correctly.

3

Load fonts at runtime

Supports dynamic font loading from files or memory (not embedded at compile time).

Enable the LVGL file system;

① File loading: lv_binfont_create ("path/font. bin");

② Memory loading: lv_binfont_create_from_buffer (buf, size); call lv_binfont_destroy () to release resources after use.

The font needs to be converted to. bin format in advance; memory must be managed manually to avoid leaks.

4

Custom Font Engine

Replace the LVGL built-in bitmap font engine (e. g., integrate FreeType to render TTF).

Implement two core callbacks:

① get_glyph_dsc_cb (returns glyph dimensions, offsets, etc.);

② get_glyph_bitmap_cb (returns glyph bitmap data).

It features high implementation complexity, and requires handling issues such as caching and Performance optimization on your own.

5

Font Fallback

When the primary font lacks certain characters, it will automatically render them using a fallback font, which is suitable for multi-language and multi-symbol scenarios.

Settings: Main Font -> fallback = Fallback Font; chaining fallback is supported (the fallback font can further set its own fallback).

Excessively long fallback chains will impact performance; it is necessary to properly plan the font coverage.

2.16.6 Core Constant Table

Constant nameValue / MeaningApplicable scenarios
LV_BASE_DIR_LTR0, left to right (default)Chinese / English / European languages
LV_BASE_DIR_RTL1, right to leftArabic / Hebrew / Persian
LV_BASE_DIR_AUTO2, auto-detectMixed-direction text
2.16.6.2 Built-in Common Font Constants (Montserrat Family)
Constant nameSize (px)Constant nameSize (px)
LV_FONT_MONTSERRAT_1212LV_FONT_MONTSERRAT_3030
LV_FONT_MONTSERRAT_1414LV_FONT_MONTSERRAT_3232
LV_FONT_MONTSERRAT_1616LV_FONT_MONTSERRAT_3434
LV_FONT_MONTSERRAT_1818LV_FONT_MONTSERRAT_3636
LV_FONT_MONTSERRAT_2020LV_FONT_MONTSERRAT_3838
LV_FONT_MONTSERRAT_2222LV_FONT_MONTSERRAT_4040
LV_FONT_MONTSERRAT_2424LV_FONT_MONTSERRAT_4242
LV_FONT_MONTSERRAT_2626LV_FONT_MONTSERRAT_4444
LV_FONT_MONTSERRAT_2828LV_FONT_MONTSERRAT_46/4846/48
Constant nameMeaningFont bpp options
LV_OPA_TRANSPFully transparent (0)1/2/4/8
LV_OPA_COVERFully opaque (255)-

2.17 Image

The "image" in LVGL is essentially a combination of bitmap data and metadata. The metadata contains key information such as dimensions and color format, and its core design revolves around "lightweight storage", "format adaptability" and "high-performance rendering" to adapt to the memory and hardware constraints of embedded scenarios.

2.17.1 Core Fundamentals: Image Storage Methods

LVGL supports two image storage formats, which are respectively adapted to the scenarios of "fixed resources" and "flexible update":

Storage methodStorage locationCore carrierAdvantagesDisadvantages
Variable storageInternal memory (RAM/ROM)lv_image_dsc_t structLinked into the program at compile time, resource usage is controllable; no extra IO needed for renderingChanging an image requires recompiling the project
File storageExternal storage (SD card / SPI Flash)LVGL file system driverImages can be updated independently without rebuilding the main programMust be loaded into RAM before rendering, IO takes time; low resource friendliness

lv_image_dsc_t Core Structure (Variable Storage Foundation)

This struct serves as the core encapsulation of memory images, with the following key fields:

2.17.2 Core Foundation: Color Format (Underlying Rules for Image Rendering)

The color format determines the encoding method of image pixels. LVGL divides them into two categories: "built-in formats" and "raw formats", which are the key to adapting images to hardware:

2.17.2.1 Built-in Color Formats (Directly Supported for Rendering)
Format categorySpecific typeCore featuresApplicable scenarios
Native formatLV_COLOR_FORMAT_NATIVEStores RGB data at the color depth configured in LVGLOrdinary color images, matching the hardware's native color depth
Native with AlphaLV_COLOR_FORMAT_NATIVE_WITH_ALPHANative format + one Alpha byte per pixelColor images with transparency
Indexed color formatLV_COLOR_FORMAT_I1/I2/I4/I8Palette mode (2/4/16/256 colors), each pixel takes 1/2/4/8 bitsImages with low color depth and few colors (such as icons)
Alpha-only formatLV_COLOR_FORMAT_A1/A2/A4/A8Stores only Alpha values, color is determined by style.img_recolorSingle-tone images whose color can change dynamically (such as font-type bitmaps)
2.17.2.2 Byte Storage Order in Native Format

Under different color depths, LV_COLOR_FORMAT_NATIVE the byte arrangement rule is as follows:

2.17.2.3 Original Format (External Decoder Required)

For common formats such as PNG and JPG that are not directly supported by LVGL, it needs to be used with the "image decoder":

2.17.3 Adding and Using Images

2.17.3.1 Two Methods for Adding Images
2.17.3.2 Core Logic of Image Usage

Render via the lv_image control, simply set the data source:

2.17.4 Image Decoder

LVGL natively only supports indexed color, native color, etc. , and external decoding libraries need to be integrated for PNG/JPG formats:

2.17.5 Image Post-processing

Adjust the image data after decoding (such as alpha premultiplication and row alignment) to adapt to hardware requirements; mark the processing status to avoid repeated operations.

2.17.6 Image Cache (Performance optimization)

2.17.7 Core Constants

CategoryConstant / MacroCore meaning
Color formatLV_COLOR_FORMAT_NATIVENative RGB, ordinary color image
NATIVE_WITH_ALPHANative RGB+Alpha, color image with transparency
I1/I2/I4/I8Indexed color, low color depth image
A1/A2/A4/A8Alpha only, single-tone image
RAW/RAW_ALPHANeeds decoding, PNG/JPG (RAW_ALPHA has transparency)
CacheLV_CACHE_DEF_SIZEDefault cache size (0, disabled)
PTR/FILECache source: memory pointer / file path
Decoder return valueLV_RESULT_OKOperation succeeded
LV_RESULT_INVALIDFormat not supported

III. Interaction and Event Handling: The Interaction Nerve of GUI

Realizing a complete interaction chain of "user operation → interface response" through input device adaptation and event mechanism is the core of the operability of GUI.

3.1 Input Device Adaptation (Input devices)

The input devices defined by LVGL are mainly divided into four categories, covering the mainstream interaction methods in embedded scenarios:

  • Supported Types: Compatible with mainstream embedded input hardware such as pointer-class devices (touch, mouse), keyboards, encoders (, etc.
  • Working Logic: Convert hardware input signals into input events recognizable by LVGL, and deliver them to the corresponding objects to implement operations such as tapping, swiping, and key pressing.

3.1.1 Core Interaction Mechanism

Category

Core Interaction Capability

Key Mechanisms / Events

Important Supplement

Pointer Devices (Pointers)

Cursor, Gesture

Cursor: An image object can be bound as the cursor for an input device;

Gesture: LV_EVENT_GESTURE is used to capture four types of gestures: up, down, left, and right

The cursor object needs to remove the "clickable" flag (disabled by default for image objects);

By default, gestures are propagated to the parent object; to prevent this propagation, you need to remove LV_OBJ_FLAG_GESTURE_BUBBLE;

Objects that are scrolling will not trigger gestures;

After handling the gesture, you can call lv_indev_wait_release to block subsequent input events.

Keyboard / Encoder (Keypad and encoder)

No cursor, relies on Group interaction

First create a group and add UI components to it;

There is always only one focused object within the group;

The input device shall be associated with a group;

Default groups can be configured

One device can only be bound to one group, while one group can receive inputs from multiple devices;

Buttons, sliders, text boxes and other controls can all be added to groups to simplify interaction development

Encoder Navigation / Edit Mode

Turn left, turn right, press

Navigation mode: Rotating left/right switches the focused object (LV_KEY_PREV / LV_KEY_NEXT), and pressing the button enters edit mode (LV_KEY_ENTER);

Edit Mode: Rotating left/right corresponds to modifying values or states (LV_KEY_LEFT / LV_KEY_RIGHT), press to return to navigation mode

The "dual mode" is used to compensate for the limitation that the encoder only has three actions: left rotation, right rotation and pressing.

Style Feedback

Interactive state-driven style changes

LV_STATE_FOCUSED : Takes effect when the object is focused via touch, keyboard or encoder;

LV_STATE_EDITED `: Takes effect when the object enters edit mode

3.1.2 Core Constants (Predefined Keys)

The core of the interaction between the keyboard / encoder lies in the key constants predefined by LVGL, which map the general interaction logic. To realize standardized interaction, it is necessary to map the hardware keys to these constants. The following is the function description of the core constants:

Constant nameFunction meaning
LV_KEY_NEXTFocus the next object in the group
LV_KEY_PREVFocus the previous object in the group
LV_KEY_ENTERTriggers press, click, long-press and other events (e.g., button click, confirm action)
LV_KEY_UPIncrease value / move up (e.g., slider up, text box cursor up)
LV_KEY_DOWNDecrease value / move down
LV_KEY_RIGHTIncrease value / move right (e.g., slider right, text box cursor right)
LV_KEY_LEFTDecrease value / move left
LV_KEY_ESCClose / exit (e.g., close dropdown list, exit current page)
LV_KEY_DELDelete the character to the right of the cursor (e.g., text box editing)
LV_KEY_BACKSPACEDelete the character to the left of the cursor (e.g., text box editing)
LV_KEY_HOMEJump to the beginning / top (e.g., text box cursor to the beginning, list to the top)
LV_KEY_ENDJump to the end (e.g., text box cursor to the end, list to the bottom)

Instructions: In the read_cb () callback function of the input device, you only need to map the core constants (NEXT/PREV/ENTER/LEFT/RIGHT) to cover most interaction scenarios; for the encoder, only the three constants LEFT/RIGHT/ENTER need to be mapped.

3.2 Event Mechanism (Events)

3.2.1 Core Definition of an Event

The event system of LVGL serves as the "nerve center" for GUI interaction, which captures various behaviors including user operations, system state changes, and widget lifecycle events, and triggers custom logic accordingly.

An event is LVGL's notification mechanism for "noteworthy behaviors or state changes", and the triggering scenarios include:

Scope of Application: Not only common controls (buttons, sliders, labels) can listen for events, but also displays and input devices can register event listeners.

The core features are as follows:

3.2.2 Event Binding and Removal

3.2.2.1 Event Binding
3.2.2.2 Event Removal

3.2.3 Event Code Classification

Event categoryEvent codeFunction description
Input device events (can be received by all widgets)LV_EVENT_PRESSEDObject is pressed (triggered once)
LV_EVENT_PRESSINGObject is being continuously pressed (triggered repeatedly while pressed)
LV_EVENT_PRESS_LOSTObject is still pressed, but the cursor / finger slides out of the object area
LV_EVENT_SHORT_CLICKEDObject is released after a short press (not triggered if scrolling occurred)
LV_EVENT_LONG_PRESSEDObject press duration reaches the long-press threshold (not triggered if scrolling occurred)
LV_EVENT_LONG_PRESSED_REPEATAfter the long-press threshold, triggered once every specified interval (not triggered if scrolling occurred)
LV_EVENT_CLICKEDTriggered on release (regardless of short or long press; not triggered if scrolling occurred)
LV_EVENT_RELEASEDTriggered in all release scenarios (including release after sliding out of the object)
LV_EVENT_SCROLL_BEGINScrolling begins; the event parameter is a pointer to the scroll animation (modifiable)
LV_EVENT_SCROLL_THROW_BEGINScroll throw begins (no additional notes)
LV_EVENT_SCROLL_ENDScrolling ends
LV_EVENT_SCROLLTriggered during scrolling
LV_EVENT_GESTUREGesture detected; the gesture direction can be obtained with lv_indev_get_gesture_dir()
LV_EVENT_KEYA key is sent to the object; the key can be obtained with lv_indev_get_key()
LV_EVENT_FOCUSEDObject gains focus
LV_EVENT_DEFOCUSEDObject loses focus
LV_EVENT_LEAVEObject loses focus but remains selected
LV_EVENT_HIT_TESTPerform advanced hit testing
LV_EVENT_INDEV_RESETInput device is reset
Draw events (can be received by all widgets)LV_EVENT_COVER_CHECKCheck whether the object fully covers an area; the event parameter is lv_cover_check_info_t *
LV_EVENT_REFR_EXT_DRAW_SIZEGet the extra drawing area needed around the object (e.g., shadow); the event parameter is int32_t * (stores the size)
LV_EVENT_DRAW_MAIN_BEGINMain drawing phase begins
LV_EVENT_DRAW_MAINPerform main drawing logic
LV_EVENT_DRAW_MAIN_ENDMain drawing phase ends
LV_EVENT_DRAW_POST_BEGINPost-drawing phase begins (after all child objects are drawn)
LV_EVENT_DRAW_POSTPerform post-drawing logic (after all child objects are drawn)
LV_EVENT_DRAW_POST_ENDPost-drawing phase ends (after all child objects are drawn)
LV_EVENT_DRAW_TASK_ADDEDTriggered when a draw task is added
Special events (widget-specific, triggered only by certain widgets)LV_EVENT_VALUE_CHANGEDObject value changes (e.g., slider drag, progress bar update)
LV_EVENT_INSERTText is inserted into the object; the event data is the inserted string (char *)
LV_EVENT_REFRESHNotifies the object to refresh its own content (for user-initiated triggering)
LV_EVENT_READYA process has completed
LV_EVENT_CANCELA process was cancelled
Other events (can be received by all widgets)LV_EVENT_CREATEObject is being created
LV_EVENT_DELETEObject is being destroyed
LV_EVENT_CHILD_CHANGEDChild object is removed / added, or its size / position changes
LV_EVENT_CHILD_CREATEDChild object is created (bubbles up to all parent objects)
LV_EVENT_CHILD_DELETEDChild object is destroyed (bubbles up to all parent objects)
LV_EVENT_SCREEN_UNLOAD_STARTScreen unload starts (triggered immediately when scr_load is called)
LV_EVENT_SCREEN_LOAD_STARTScreen load starts (triggered after the screen switch delay expires)
LV_EVENT_SCREEN_LOADEDScreen load finished
LV_EVENT_SCREEN_UNLOADEDScreen unload finished
LV_EVENT_SIZE_CHANGEDObject coordinates / size changed
LV_EVENT_STYLE_CHANGEDObject style changed
LV_EVENT_LAYOUT_CHANGEDChild object position changed due to layout recalculation
LV_EVENT_GET_SELF_SIZEGet the widget's internal self size
Display event (received only by display objects)LV_EVENT_INVALIDATE_AREADisplay area invalidated (needs redraw)
LV_EVENT_RESOLUTION_CHANGEDDisplay resolution changed
LV_EVENT_COLOR_FORMAT_CHANGEDDisplay color format changed
LV_EVENT_REFR_REQUESTDisplay requests refresh
LV_EVENT_REFR_STARTDisplay refresh starts
LV_EVENT_REFR_READYDisplay refresh ready
LV_EVENT_RENDER_STARTDisplay rendering starts
LV_EVENT_RENDER_READYDisplay rendering ready
LV_EVENT_FLUSH_STARTDisplay flush starts
LV_EVENT_FLUSH_FINISHDisplay flush finished
Custom event (registered by the user, not triggered by LVGL itself)Custom event code1. Register a custom event code via lv_event_register_id() (e.g. uint32_t MY_EVENT_1 = lv_event_register_id()); 2. Send it manually to any object via lv_event_send(obj, custom event code, &data)

Of course, there are also manually dispatched events and the special Refresh event:

Event categoryCore API / trigger methodFunction descriptionExample scenario
Send event manually (general)1. Widget: lv_obj_send_event(obj, <EVENT_CODE>, &some_data)
2. Display: lv_display_send_event(obj, <EVENT_CODE>, &some_data)
3. Input device: lv_indev_send_event(obj, <EVENT_CODE>, &some_data)
Actively triggers the target event on the specified object and can pass custom data; used to simulate user actions / system state changes instead of triggering the event through real interactionSimulate a button press: send LV_EVENT_VALUE_CHANGED with the button ID to close the message box manually
Refresh special event (LV_EVENT_REFRESH)Must be sent manually via lv_obj_send_event() (LVGL does not trigger this event automatically)A refresh notification mechanism designed for the user, used to tell an object to update its own state, appearance or business logic1. A label refreshes its text from a variable (e.g. showing the real-time clock)
2. Refresh a label's displayed text when the language changes
3. Enable a button after the correct PIN is entered
4. Add / remove a warning style on an object when a value exceeds its limit

3.2.4 lv_event_t: Core Parameter for Event Callbacks

3.2.4.1 Core Concepts

In LVGL development with MicroPython (MPY), event_t (corresponding to lv_event_t in C language) is the only parameter received by the event callback function, which encapsulates all context information of the event, including event type, triggering object, custom data, etc.

MPY wraps the C-language lv_event_get_xxx (e) function form into a event_t class member method (such as e.get_code ()) that better conforms to Python syntax; it has no pointer concept, and all return values are class instances encapsulated by LVGL-MPY (such as the widget object obj and the area object area_t), serving as the "core hub" for event processing.

3.2.4.2 Summary Table of Core Methods
CategoryMethod name (MPY)Core meaningTypical use case / notes
Basic core methods (must know)get_code()Get the event code that triggered the current callback (e.g. LV_EVENT_CLICKED/LV_EVENT_VALUE_CHANGED)Branching in a callback: "run logic A on a click event, run logic B on a value-changed event"
get_target() / get_target_obj()Get the widget object that originally triggered the event (with event bubbling, still returns the original child widget)When a parent container listens to child widget events, pinpoints "who triggered the event"
get_current_target() / get_current_target_obj()Get the widget object currently handling the event (with event bubbling, returns the parent container when the parent handles it)Same return value as get_target_obj() when there is no bubbling; with bubbling, distinguishes the "trigger" from the "handler"
get_user_data()Get the custom user data passed when the event was bound (e.g. button ID, config dict)Multiple widgets share one callback and use user_data to distinguish the handling logic
get_param()Get the event parameter passed when the event was sent manually (e.g. the button ID of a simulated button click)Pass data when triggering an event manually to implement custom interaction
Event flow controlstop_bubbling()Stop the event from bubbling up (the parent container no longer receives it)After a child widget handles the event, prevents the parent container from responding again
stop_processing()Terminate all subsequent event callbacks of the current objectAfter the event is handled, stop redundant callback execution
Input device relatedget_indev()Get the input device object that triggered the event (touchscreen / key / encoder)Distinguish the event source: determine whether it was triggered by touch or by a key
get_key()Get the key value of an LV_EVENT_KEY event (integer type)Key interaction: determine whether the confirm key / back key / arrow key was pressed
get_rotary_diff()Get the increment of a rotary encoder (positive or negative indicates rotation direction)Encoder interaction: adjust volume / slider value based on the increment
Scroll / animation relatedget_scroll_anim()Get the animation object of the scroll animation (anim_t)Custom scroll animation: modify scroll duration / easing curve
Drawing / layout specific (custom widgets)set_ext_draw_size(size)Set the extra draw area size of the widget (e.g. the area that a shadow / border extends beyond)When a custom widget adds a shadow, specify the extra drawing space
get_self_size_info()Get the widget's self size information (point_t, x = width / y = height)Custom scroll container: calculate the actual content size and trigger scroll logic
get_hit_test_info()Get hit test information (hit_test_info_t)Custom clickable area: e.g. a circular widget responds only to clicks within the circle
get_cover_area()Get the widget's cover area (area_t)Drawing optimization: determine whether the widget covers other widgets and skip unnecessary drawing
set_cover_res(res)Set the cover check result (fully covered / partially covered / not covered)Tell LVGL the widget's cover status to reduce drawing overhead
get_draw_task()Get the current draw task object (draw_task_t)Custom drawing flow: modify draw priority / content
Extended information retrievalget_invalidated_area()Get the screen invalidated area when the event is triggered (area_t)Drawing optimization: redraw only the areas that need updating
get_layer()Get the layer object the widget belongs to (layer_t)Multi-layer management: determine whether the widget is on a normal layer / top layer
get_old_size()Get the widget's old size before the size change (area_t)Size change event: compare the size before and after modification

3.2.5 Event Bubbling

Event bubbling is a mechanism designed by LVGL for hierarchical controls to propagate events upwards:

The key method to enable event bubbling is add_flag:

02 LVGL Basic Knowledge and Concepts

Core event methods for bubbling scenarios (distinguishing between "current target" and "original target"):

Method (MPY)FunctionKey role in bubbling scenarios
event.get_current_target_obj()Get the object currently handling the eventWhen bubbling to a parent container, returns the parent container; when bubbling to the screen, returns the screen
event.get_target_obj()Get the child object that originally triggered the eventRegardless of the level it bubbles to, always returns the widget that originally triggered the event (e.g. the clicked button)

IV. Display and Multi-Screen Management: GUI Output Window

In LVGL, the Display (display device) is the hardware-level pixel output carrier (physical screen, virtual screen such as VNC), responsible for flushing UI rendering results to the screen;The Screen is a root container object at the UI level, one display device can be bound to multiple Screens, the Screen has no parent object, and its size completely matches the affiliated display device.

The differences between the two are as follows:

DimensionDisplay (display device)Screen
EssencePhysical / virtual hardware, responsible for drawing pixelsTop-level root container of the UI, has no parent object
Size propertyFixed hardware resolutionSize = that of its display device; coordinates cannot be modified
Ownership1 display can have multiple Screens bound to it1 Screen belongs to only 1 display
Operation limitsConfigure driver, buffers, background, etc.Position / size cannot be changed; can be loaded / deleted

4.1 Multi-display Device Support

LVGL natively supports multiple independent display devices, each of which can have its own dedicated driver, UI interface and color depth without interfering with each other:

4.2 Use of a single display device

In most embedded scenarios, only a single display device is required, and LVGL will completely hide the complex logic related to multi-display in such cases:

4.3 Mirror Display and Split-Screen Splicing

4.4 Transparent Screen

5. Timing and Dynamic Effects: The Dynamic Engine of GUI

5.1 Timers

The timer system built into LVGL is a core tool for implementing "periodic tasks" and "delayed execution" in embedded UI development, especially in MPY/MicroPython scenarios. Its design adapts to the lightweight requirements of embedded systems and follows the "non-preemptive" principle, which ensures the security of LVGL API calls and eliminates concerns about UI exceptions caused by timer interrupts.

5.1.1 Core Principle of Timer

The LVGL timer is not a hardware timer, but a task scheduling tool at the software level, which relies on the lv_timer_handler () function at its core:

02 LVGL Basic Knowledge and Concepts

Meanwhile, the LVGL timer is "non-preemptive":

5.1.2 Timer Creation

LVGL provides two creation methods to adapt to different configuration requirements:

5.1.2.1 Create with Parameters

Key parameters can be directly specified when created via the core function, and will take effect immediately after creation:

5.1.2.2 Base Creation

Create an "empty timer via lv_timer_create_basic (), then dynamically configure parameters such as callback function, period, and user data after creation. This approach is suitable for scenarios where you need to create the object first and adjust parameters later according to business logic.

5.1.3 Basic Operations of Timer (Configuration and Control)

Serial No.

Functions

Description

Scenarios / Examples

Notes

1

Ready and Reset

(Trigger and Cycle Reset)

lv_timer_ready (timer) forces the timer to execute its callback once during the next lv_timer_handler () call, ignoring the current cycle progress;lv_timer_reset (timer) resets the timer's cycle count and clears the current progress to zero.

ready is suitable for scenarios where there is no need to wait for the end of the cycle and a task needs to be triggered immediately, such as manually refreshing the UI and forcing data update;reset is suitable for resetting periodic tasks after user operations, for example, triggering a search 500ms after the input box stops receiving input, and resetting the timer when a new character is entered.

ready means "schedule the next execution immediately";reset means "restart the timer".

2

Dynamically modify timer parameters

After a timer is created, its core parameters can be modified at any time without the need to recreate the timer.

You can modify the callback function to replace the logic executed when the timer is triggered; you can also modify the period to adjust the callback execution interval, for example, changing it from 500ms to 1000ms.

The behavior of the timer will immediately take effect according to the new parameters after modification.

3

Repetition Count Control

You can use lv_timer_set_repeat_count () to limit the execution times of the timer.

Set it to a specific value (e. g. 5), which means the timer will be automatically deleted after the callback is executed 5 times; set it to -1, which means infinite loop execution. Typical scenarios include one-off delayed tasks (set to 1) and finite-loop tasks (e. g. stop after a 5-count countdown).

-1 is the default infinite loop behavior; once set to a finite number of times, it will be automatically deleted after execution is completed.

5.1.4 Start, Stop, Pause and Resume of Timers

Serial No.

Functions

API

Description

Features

Applicable Scenarios

1

Enable / Disable

lv_timer_enable(timer) / lv_timer_disable(timer)

After the timer is enabled, periodic execution resumes; after the timer is disabled, execution stops and the periodic timer is reset.

When disabled, the timing progress will be reset to zero; when re-enabled, timing will start from 0.

Suitable for long-term switching timers, such as the main function switch (which stops completely after being turned off and restarts timing after being turned on again).

2

Pause / Resume

lv_timer_pause(timer) / lv_timer_resume(timer)

Pausing the timer will stop the execution while retaining the current timing progress; after resuming, the timing will continue from the paused position.

The progress remains unchanged after pausing; after resuming, the callback will be triggered once the remaining cycle is completed.

It is applicable to temporarily suspending tasks, such as pausing the animation timer when a pop-up window blocks the view and resuming it after the window is closed.

5.1.5 Idle Time Measurement

lv_timer_get_idle () is used to obtain the idle time proportion of lv_timer_handler ():

5.1.6 Timer Handler Recovery Callback

When lv_timer_handler () is stopped (e. g., during system sleep), if you need to monitor its "wake-up timing"(i. e., when lv_timer_handler () resumes being called), you can set a resume callback:

5.1.7 Asynchronous Call

Asynchronous invocation is an extended capability of the timer system, which addresses the issue of "being unable to execute a certain operation immediately", with the core being "to defer the task to the next lv_timer_handler () invocation for execution".

5.2 Animation System (Animations)

The core of LVGL's animation system lies in automatically and periodically modifying the attribute values of target objects (such as the coordinates, dimensions, and opacity of controls). It achieves visual dynamic effects by binding an "execution callback", eliminating the need for manual loop control throughout the process, and features lightweight performance and ease of use adapted to embedded (MPY) scenarios. Following a design logic of "defining animation rules via configuration for automatic execution by the framework", it supports single-attribute animations and composite timeline animations, while allowing highly customized dynamic effect styles.

5.2.1 Core Principles of Animation

5.2.2 Creation and Configuration of Single Animation

The core of creating an animation follows the workflow of "initialization → configure rules → launch". All rules are defined via configuration items, which are divided into mandatory configurations (animation fundamentals) and optional configurations (customized animation effects).

5.2.2.1 Mandatory Configuration

This is the foundation for the animation to function, defining "what to modify, which object to modify, how long the modification lasts, and the start and end points of the modification":

Configuration itemCore meaning
Execution callbackSpecifies the "function that modifies the property" (e.g. lv_obj_set_x to change the x coordinate); it is the "action carrier" of the animation;
Target objectSpecifies the widget the animation acts on (e.g. a button or label);
Animation durationTotal time the animation takes from start value to end value (unit: ms);
Start and end valuesDefines the start and end values of the property (e.g. x coordinate from 0 to 150).
5.2.2.2 Optional Configuration

These configurations enable richer animation behaviors to adapt to different UI scenarios:

Configuration itemCore meaningApplicable scenarios
Start delayWait time before the animation starts (ms);Multiple animations triggered in sequence (e.g., play B only after A finishes);
Animation path (curve)Defines the pacing of value transitions (e.g., linear, ease-in, overshoot);Improves animation feel (e.g., overshoot for button clicks, ease-in for swipes);
Completion callbackFunction triggered when the animation ends;Run follow-up logic after the animation ends (e.g., load content after a popup animation finishes);
Delete callbackFunction triggered when the animation is deleted;Release animation-related resources;
Start callbackFunction triggered when the animation actually starts (after the delay ends);Record the animation start state;
Playback-reverse durationDuration of reverse playback (end value → start value) after the animation ends (0 disables);Back-and-forth animation (e.g., a popup retracts automatically after appearing);
Playback-reverse delayHow long to wait after the forward animation ends before reverse playback starts;Controls the interval of back-and-forth animation;
Repeat countNumber of times the animation repeats (LV_ANIM_REPEAT_INFINITE for infinite loop);Looping animation (e.g., loading animation);
Repeat delayWait time before each repeat;Controls the interval of looping animation;
Apply start value earlyIf enabled, the start value is applied immediately; if disabled, it is applied after the delay ends;Avoids abnormal target property values during the delay;
5.2.2.3 Animation Startup

After completing all configurations, call the start function to trigger the animation; the framework will automatically handle numerical calculation and callback invocation without manual intervention.

5.2.3 Animation Path (Motion Effect Curve) — Controlling the Gradient Rhythm

Animation path is a function that calculates the current value based on the animation progress, which determines the "feel" of the animation effect. LVGL has multiple built-in common paths that cover most scenarios:

Built-in pathTransition pacing characteristicsTypical application scenarios
linearLinear transition (constant speed)Constant-speed movement and scaling (e.g., slider sliding);
stepHolds the start value throughout, then jumps to the end value on the last step;Instant-switch animation (e.g., toggle state change);
ease_inSlow at the start, faster afterward;Page slide-in (slow to fast, more natural);
ease_outFast at the start, slow at the end;Page slide-out (fast to slow, not abrupt);
ease_in_outSlow at both the start and end, fast in the middle;Widget translation (the most general smooth animation);
overshootOvershoots the end value, then bounces back to the target value;Emphasis animation (e.g., button click, popup appearing);
bounceBounces slightly a few times after reaching the end value;Physical-feel animation (e.g., an object landing, click feedback);

5.2.4 Conversion between Speed and Time

The default animation defines the total duration via "duration", but in some scenarios, "speed"(e. g. moving 20 pixels per second) is more intuitive. LVGL provides a conversion function for this:

5.2.5 Deletion of Animations

If you need to stop the animation midway, you can delete it by using the combination of "target object + execution callback"(this is the unique identifier of the animation); once deleted, the animation will stop immediately and trigger the "deletion callback"(if configured).

5.2.6 Timeline — Composite Animation Scheduling

0 700ms 6 1 obj1 0ms 2 3 obj2 200ms

When it is necessary to implement "dynamic effects of multiple controls and multiple attributes according to a specific timeline"(such as boot guide animations and combined pop-up dynamic effects), a single animation is difficult to manage. LVGL provides the "timeline" function, which integrates multiple animations into a whole according to the timeline:

5.2.6.1 Core Value of the Timeline
5.2.6.2 Process for Creating and Using Timelines
  1. Create a single animation: Define each sub-animation according to the configuration rules for a single animation, but do not start it;
  2. Create a timeline object: Initialize an empty timeline container;
  3. Add sub-animations to the timeline: Specify the "start time on the timeline" for each sub-animation (this time will override the sub-animation's own delay configuration);
  4. Start Timeline: Triggers the entire composite animation, and the framework will automatically execute each sub-animation according to the timeline;
5.2.6.3 Core Operations of the Timeline
OperationFunction description
Reverse playbackReverses the whole timeline (e.g., runs from the last animation back to the first);
Set progressJump directly to a specified progress on the timeline (e.g., start playing from 50% progress);
Get total durationCheck the total time of the entire timeline;
Stop timelinePause all child animations;
Delete timelineDestroy the timeline and all child animations (important: before deleting a widget that is being animated, delete the timeline first to avoid a crash);

VI. Underlying Rendering and Performance Optimization: The Performance Foundation of GUI

It handles the underlying logic of graphics rendering, provides hardware acceleration and performance analysis tools, and balances feature richness with hardware resource consumption.

6.1 Drawing Mechanism (Drawing)

With VGL, you don’t need to draw anything manually. Simply create controls such as buttons, labels and arcs, adjust their positions and styles, and VGL will automatically refresh and redraw the parts that require updating.

6.1.1 Core Rendering Approach: Draw to the Buffer First, Then Update the Screen

LVGL does not draw directly on the screen; instead, it first renders content in an internal "drawing buffer", and once rendering is complete, it copies the buffer contents to the screen. This buffer can be smaller than the screen, and LVGL will divide the frame into small segments (tiles) to match the buffer size.

6.1.2 How to refresh the screen? Only update the areas that need to be changed

When there are changes in the UI (such as a button being clicked or an animation playing), LVGL will refresh according to the following steps:

6.1.3 Mask: The Core of Creating Fancy Styles

Masking is the underlying logic for LVGL to draw graphics and text. You can use it without understanding the principle, but it is very useful when customizing styles:

6.1.4 Custom Drawing: Hook Events Help You Tweak Details

If you want to implement special styles (for example, changing the color of a single button in a matrix button independently), you can use LVGL's "draw hook event":

6.2 Profiler

192us

LVGL has a built-in profiler, which is specifically designed to troubleshoot performance issues such as low frame rate, laggy performance and cache invalidation that arise as projects grow more complex. It tracks the timestamps of key runtime events including rendering and user input, stores the data in a buffer of configurable size, outputs logs in the Android systrace format, and allows users to visualize and check time consumption via the Perfetto tool;When in use, you need to enable the feature in the configuration file, where you can set the buffer, high-precision timestamp, and custom log output mode. You can also manually add measurement points to the function, and it supports integration with the analyzer built into the operating system. Meanwhile, there are corresponding solutions for common issues such as log parsing failure, displayed time consumption of 0, laggy analysis, and no log output.

6.3 Rendering and GPU Acceleration

LVGL supports multiple rendering solutions, ranging from pure software rendering to hardware GPU acceleration, and is compatible with various platforms (including embedded MCUs, desktop simulators, etc.), with the core goal of improving UI rendering performance and reducing CPU usage.

The renderers / GPUs of LVGL fall into three categories:

The differences are as follows:

Renderer / GPUSupported platformsCore characteristicsRequired hardware / instruction set
Software rendererAll platforms (generic)Pure CPU drawing, best compatibility, average performanceNone (pure software)
SDL rendererDesktop / simulator (PC, Mac, etc.)Hardware-accelerated, smooth for development and debugging, suited to simulatorsSDL library + desktop GPU
Arm-2D GPUARM Cortex-M, all series2D acceleration abstraction layer, with synchronous / asynchronous modes, requires hardware / instruction setCortex-M + Helium/ACI or DMAC-350, etc.
NXP PXP GPUNXP i.MX RT and similar platformsHardware 2D acceleration, reduces CPU usage, optimized for NXP devicesNXP PXP hardware module
DMA2D GPUSTM32 (H7/F7, etc.)Hardware 2D acceleration, memory copy / blending, frees the STM32 CPUSTM32 DMA2D hardware module
NXP VGLite GPUHigh-end NXP i.MX RT and similarHardware 2D/3D acceleration, supports complex graphics, higher performanceNXP VGLite GPU hardware module

VII. Extensibility and Customization Capabilities: GUI Extension Interfaces

It provides resource loading and custom development capabilities to meet the personalized needs of business scenarios.

7.1 File System

The file system module of LVGL is a hardware-independent abstraction layer, whose core purpose is to mask the underlying differences between various storage media (such as SD cards, SPI Flash, local disks) and file systems (such as FATFS, POSIX-compliant file systems), so as to provide a unified file operation interface for upper-layer applications (such as image loading, file reading and writing).

7.1.1 Core Design Concept

02 LVGL Basic Knowledge and Concepts
D1 D2

7.1.2 Ready-made Drivers (Out Of The Box)

LVGL comes with built-in drivers adapted for mainstream file systems and platforms, eliminating the need to manually implement core callbacks, which can be directly reused:

7.1.3 Add Custom File System Driver

If the built-in driver cannot meet the requirements (e. g. the SPI Flash file system adapted to the MPY platform), you need to manually register a custom driver, and the core process is as follows:

7.1.3.1 Driver Structure Initialization

You need to first create a driver struct (which shall be allocated globally or statically to avoid invalidation caused by the destruction of local variables) and complete the basic initialization:

7.1.3.2 Bind Core Callback Function

The core capabilities of the driver are implemented by callback functions, which are divided into file operations and directory operations two categories, and can be bound as needed:

Callback typeCore callbacksFunction description
Basic ready checkready_cbTells LVGL whether the storage device for this driver is ready (e.g., whether an SD card is inserted)
Core file operationsopen_cbOpen file: takes the "path with the driver letter removed" + "open mode (read / write)" and returns a file object pointer (used by subsequent operations)
close_cbClose file: releases the resources acquired when the file was opened
read_cbRead file: reads a specified number of bytes from an opened file
write_cbWrite file: writes a specified number of bytes to an opened file
seek_cbMove file pointer: adjusts the file read/write position
tell_cbGet file pointer position: returns the offset of the current read/write pointer in the file
Directory operationsdir_open_cbOpen directory: prepares to iterate over directory contents
dir_read_cbRead directory: reads file / subdirectory names in the directory in a loop (a "/" prefix is recommended to mark directories)
dir_close_cbClose directory: releases the resources used for directory iteration
7.1.3.3 Register the driver

After completing the structure configuration and callback binding, register the driver with the LVGL kernel, after which you can access this file system via the drive letter.

7.1.4 Core Logic of Callback Function

All callback designs are centered around the "file object", with the core rules as follows:

7.1.5 Core Usage Logic of the File System

7.1.5.1 File Operation Process (Read/Write)

Regardless of the underlying storage type, the upper-layer operation process remains unified:

7.1.5.2 Directory Operation Procedure

Process for traversing directory contents:

7.1.5.3 Core Modes / Result Codes

7.1.6 Key Requirements for Image Controls to Use the File System

To make the LVGL image widget load images from files (instead of variables compiled into the program), the following 4 callbacks must be implemented, and none of them can be missing:

7.2 Custom Extensions

Version Record

Version Number

Modifier

Time

Content

v1.0

Li Zisheng

2026/03/18

Initialize the document.