Jetpack Compose下Lottie动画运行时动态修改文本及图片的实现问题
Jetpack Compose Lottie 动态修改文本与图片实现方案
一、动态修改动画内部文本
首先确保项目依赖的 lottie-compose 版本在6.0.0及以上,Compose侧已原生提供文本代理能力,无需适配传统View体系的TextDelegate:
- 提前和设计师确认Lottie文件内需要修改的文本图层的准确命名,比如领奖台场景的前三名姓名字段可约定为
first_name、second_name、third_name - 通过
rememberLottieTextDelegate定义文本映射关系,支持绑定动态State实现后端数据返回后自动更新:
// 后端返回后可直接更新这三个State变量,文本会自动同步到动画中 val firstName by remember { mutableStateOf("") } val secondName by remember { mutableStateOf("") } val thirdName by remember { mutableStateOf("") } val textDelegate = rememberLottieTextDelegate( "first_name" to firstName, "second_name" to secondName, "third_name" to thirdName )
- 将textDelegate传入
LottieAnimation组件的对应参数即可生效:
LottieAnimation( composition = lottieComposition, progress = { animationProgress }, textDelegate = textDelegate )
二、动态替换动画内部图片资源
官方提供了专门的图片资产代理方案,适配Compose场景:
- 提前确认Lottie文件内需要替换的图片资产ID,同样和设计师导出时的命名保持一致,比如前三名头像资产可约定为
first_avatar、second_avatar、third_avatar - 通过
rememberLottieImageAssetDelegate定义图片映射关系,支持传入Bitmap、Drawable、Painter等多种类型的图片资源:
// 假设这三个Bitmap是从后端加载得到的头像资源 val firstAvatarBitmap: Bitmap? by remember { mutableStateOf(null) } val secondAvatarBitmap: Bitmap? by remember { mutableStateOf(null) } val thirdAvatarBitmap: Bitmap? by remember { mutableStateOf(null) } val imageDelegate = rememberLottieImageAssetDelegate { asset -> when (asset.id) { "first_avatar" -> firstAvatarBitmap "second_avatar" -> secondAvatarBitmap "third_avatar" -> thirdAvatarBitmap else -> null // 返回null时会使用Lottie内置的默认图片资源 } }
- 将imageDelegate传入
LottieAnimation组件的对应参数即可生效:
LottieAnimation( composition = lottieComposition, progress = { animationProgress }, textDelegate = textDelegate, imageAssetDelegate = imageDelegate )
注意事项
- 如果需要调整文本的字号、颜色、字体等样式,可以通过
rememberLottieDynamicProperty绑定对应文本图层的属性实现修改 - 若使用的
lottie-compose版本较低暂不支持上述API,可临时通过AndroidView包裹传统LottieAnimationView,使用原有TextDelegate和图片替换方案实现,长期建议升级到最新稳定版 - 后端加载的图片资源建议提前做缓存处理,避免重复请求导致动画加载延迟
内容的提问来源于stack exchange,提问作者Murillo Minuscoli Maciel
相关产品推荐
相关产品推荐

