You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中Lottie动画动态文本与自定义字体问题

解决Jetpack Compose中Lottie无字形动画的文本替换问题

核心问题分析

你遇到的空白问题主要来自两个关键点:fontMap的键值不匹配,以及Compose代码中误用了带字形的Lottie文件。以下是具体的修复步骤和代码示例:


步骤1:确认Lottie文件的字体标识

打开你的无字形Lottie JSON文件(testing_no_glyphs.json),找到字体定义节点,示例结构如下:

"assets": [
  {
    "id": "font_0",
    "font": {
      "fName": "YourTargetFontName", // 这就是fontMap需要的键
      "fFamily": "YourFontFamily",
      "fStyle": "Regular",
      "ascent": 100
    },
    "type": "font"
  }
]

fName字段的值就是fontMap必须使用的键,大小写和字符必须完全匹配。


步骤2:修正Compose代码

使用无字形Lottie文件,配合正确的fontMap键和动态文本配置:

import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.airbnb.lottie.compose.rememberLottieDynamicProperties
import com.airbnb.lottie.compose.rememberLottieDynamicProperty
import com.airbnb.lottie.utils.LottieConstants
import com.airbnb.lottie.LottieProperty
import android.graphics.Typeface

// 你的Compose组件内
val context = LocalContext.current
val customTypeface = remember {
    Typeface.createFromAsset(context.assets, "fonts/[MyFontInside /assets].ttf")
}

val dynamicProperties = rememberLottieDynamicProperties(
    rememberLottieDynamicProperty(
        property = LottieProperty.TEXT,
        value = "AaBbCcEeFf",
        // 确保KeyPath与Lottie文件中的文本层名称完全一致
        keyPath = arrayOf("Test234")
    ),
    // 可选:单独给目标文本层指定字体,避免fontMap匹配问题
    rememberLottieDynamicProperty(
        property = LottieProperty.TEXT_TYPEFACE,
        value = customTypeface,
        keyPath = arrayOf("Test234")
    )
)

val composition by rememberLottieComposition(
    spec = LottieCompositionSpec.RawRes(R.raw.testing_no_glyphs) // 必须用无字形版本
)

val progress by animateLottieCompositionAsState(
    composition = composition,
    iterations = LottieConstants.IterateForever
)

LottieAnimation(
    composition = composition,
    progress = { progress },
    dynamicProperties = dynamicProperties,
    // 使用Lottie JSON中获取的fName作为键
    fontMap = mapOf("YourTargetFontName" to customTypeface)
)

关键注意事项

  1. 依赖版本验证:确保使用5.3.0-SNAPSHOT版本的Lottie Compose,同时在项目仓库中配置快照源:
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    }
    
    dependencies {
        implementation "com.airbnb.android:lottie-compose:5.3.0-SNAPSHOT"
    }
    
  2. KeyPath精确性:如果文本层嵌套在父图层下,KeyPath需要写成arrayOf("父图层名称", "Test234"),可以通过LottieFiles在线编辑器确认图层路径。
  3. 避免带字形文件:必须使用无字形导出的Lottie文件,否则无法支持任意字符替换。

内容的提问来源于stack exchange,提问作者Phehaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:50:10