1 package com.airbnb.lottie.sample.compose.examples
2
3 import android.graphics.Typeface
4 import androidx.compose.foundation.layout.Column
5 import androidx.compose.foundation.layout.fillMaxWidth
6 import androidx.compose.foundation.rememberScrollState
7 import androidx.compose.foundation.verticalScroll
8 import androidx.compose.runtime.Composable
9 import androidx.compose.runtime.LaunchedEffect
10 import androidx.compose.runtime.getValue
11 import androidx.compose.runtime.mutableStateOf
12 import androidx.compose.runtime.remember
13 import androidx.compose.runtime.setValue
14 import androidx.compose.ui.Modifier
15 import androidx.compose.ui.platform.LocalContext
16 import com.airbnb.lottie.LottieProperty
17 import com.airbnb.lottie.compose.LottieAnimation
18 import com.airbnb.lottie.compose.LottieCompositionSpec
19 import com.airbnb.lottie.compose.rememberLottieComposition
20 import com.airbnb.lottie.compose.rememberLottieDynamicProperties
21 import com.airbnb.lottie.compose.rememberLottieDynamicProperty
22 import com.airbnb.lottie.sample.compose.R
23 import kotlinx.coroutines.Dispatchers
24 import kotlinx.coroutines.withContext
25
26 @Composable
TextExamplesPagenull27 fun TextExamplesPage() {
28 UsageExamplePageScaffold {
29 Column(
30 modifier = Modifier
31 .fillMaxWidth()
32 .verticalScroll(rememberScrollState())
33 ) {
34 ExampleCard("Default", "Loading fonts using default asset paths") {
35 Example1()
36 }
37 ExampleCard("Dynamic Properties", "Replace fonts with custom typefaces") {
38 Example2()
39 }
40 }
41 }
42 }
43
44 @Composable
Example1null45 private fun Example1() {
46 // Lottie will automatically look for fonts in src/main/assets/fonts.
47 // It will find font files based on the font family specified in the Lottie Json file.
48 // You can specify a different assets subfolder by using the fontAssetsFolder parameter.
49 // By default, it will look for ttf files.
50 // You can specify a different file extension by using the fontFileExtension parameter.
51 val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.name))
52 LottieAnimation(
53 composition,
54 progress = { 0f },
55 )
56 }
57
58 @Composable
Example2null59 private fun Example2() {
60 val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.name))
61 val typeface = rememberTypeface("fonts/Roboto.ttf")
62 val dynamicProperties = rememberLottieDynamicProperties(
63 rememberLottieDynamicProperty(LottieProperty.TYPEFACE, typeface, "NAME")
64 )
65
66 LottieAnimation(
67 composition,
68 progress = { 0f },
69 dynamicProperties = dynamicProperties,
70 )
71 }
72
73 @Composable
rememberTypefacenull74 private fun rememberTypeface(path: String): Typeface? {
75 var typeface: Typeface? by remember { mutableStateOf(null) }
76 val context = LocalContext.current
77 LaunchedEffect(path) {
78 typeface = null
79 withContext(Dispatchers.IO) {
80 typeface = Typeface.createFromAsset(context.assets, "fonts/Roboto.ttf")
81 }
82 }
83 return typeface
84 }