LVGL Pro使用指南[13] LVGL XML 动画
概述 链接到标题
LVGL 的 XML 动画基于时间轴动画(Timeline Animations),时间轴由多个简单的动画组成。每个组件(Component)可以定义自己的时间轴动画,这些动画可以由组件自身或父组件触发。动画的典型示例包括改变某个属性(如透明度 opa 或位置 translate_x)从一个值到另一个值,持续一定时间(如 500 毫秒)。
定义时间轴 链接到标题
时间轴可以在 <screen> 和 <component> 中定义,对于 <widget>,仅在 LVGL Pro Editor 中支持,并且可以从中导出 C 代码。时间轴由 <timeline> 标签定义,每个时间轴可以包含多个 <animation> 标签,描述具体的动画步骤。
<animation> 属性:
prop:要动画化的样式属性,支持所有整数、百分比和颜色样式属性。selector:样式选择器,默认为 main|default。target:要动画化的 UI 元素的名称,self 表示组件的根元素(即<view>)。start和end:动画元素的起始值和结束值,必须是整数。duration:动画持续时间(毫秒)。delay:动画开始前的延迟(毫秒),不设置则默认为 0。early_apply:如果为 true,起始值会在延迟期间立即生效,默认为 false。
可以通过 <include_timeline> 在时间轴中引用其他组件的时间轴,实现动画的复用。例如 my_icon 定义了一个名为 "show_up" 的时间轴,用于图标的淡入和放大动画。这些动画都封装在 my_icon.xml 中,可以在其他时间轴中引用 show_up。<include_timeline> 需要使用以下属性:
target:目标 UI 元素的名称,其时间轴将被包含。self指组件的根元素(即<view>)。timeline:要包含的时间轴名称,必须在目标元素的 XML 文件中定义。delay:开始前的延迟时间(毫秒),默认值为 0。
示例如下:
<component>
<animations>
<!-- Show the component and its children -->
<timeline name="load">
<animation prop="translate_x" target="self" start="-30" end="0" duration="500"/>
<animation prop="opa" target="text" start="0" end="255" duration="500" delay="200"/>
<include_timeline target="icon" timeline="show_up" delay="300"/>
</timeline>
<!-- Shake horizontally -->
<timeline name="shake">
<animation prop="translate_x" target="self" start="0" end="-30" duration="150"/>
<animation prop="translate_x" target="self" start="-30" end="30" duration="300" delay="150"/>
<animation prop="translate_x" target="self" start="30" end="0" duration="150" delay="450"/>
</timeline>
</animations>
<view>
<lv_button width="200">
<my_icon name="icon" src="image1"/>
<lv_label name="text" text="Click me"/>
</lv_button>
</view>
</component>
load 的时间轴包含三个动画动作:
- 按钮(
target="self")在 x 轴上(prop="translate_x")从 -30(start="-30")滑动到 0(end="0"),整个过程持续 500ms(duration="500") - 按钮上 text 对象(
target="text")的透明度(prop="opa")从 0(start="0")变到 255(end="255"),动画在 200ms 后才开始执行(delay="200"),整个过程执行 500ms(duration="500") - 第三个动画通过包含(
include_timeline)show_up 的时间轴(timeline="show_up"),动画对象是按钮上的 icon(target="icon"),show_up 的时间轴在 300ms 后才开始执行(delay="300")
播放时间轴 链接到标题
通过在控件(Widget)下添加 <play_timeline_event> 标签,标签内描述的事件可以触发播放时间轴(Timelines)。下面是在按钮点击时播放 bounce 时间轴的示例:
<view>
<lv_label name="title" text="Hello world!"/>
<custom_button name="button" y="20">
<play_timeline_event trigger="clicked" target="button" timeline="bounce"/>
<lv_label text="Click me"/>
</custom_button>
</view>
可以为一个目标 UI 元素设置要播放的时间轴(timeline)。如果设置 target="self",则会在当前组件 / 小部件 / Screen(即当前 XML 文件中)查找该时间轴。
还可以在播放时间轴时设置 delay(延迟)和 reverse="true"(反向播放)等参数。
内部工作原理 链接到标题
了解内部机制有助于更高效地使用时间轴。当 XML 文件被注册时,<animations> 部分的内容被解析,时间轴数据以"蓝图"(blueprint)形式存储,目标名称以字符串形式保存。当组件或 Screen 的实例被创建时,lv_anim_timeline 从保存的"蓝图"中创建并初始化。如果使用了 <include_timeline>,则在此时将请求的时间轴包含到组件的时间轴中。创建的时间轴实例及其名称保存在组件实例中,每个实例都有自己的时间轴,因此可以独立播放多个组件的时间轴。当在某个 UI 元素中添加 <play_timeline_event> 时,其目标对象名称和时间轴名称会以字符串形式保存,因为事件可能引用尚未创建的 UI 元素。当触发播放时间轴事件时,根据名称从目标中检索时间轴,并根据其他参数(如反向、延迟等)启动。