Boring preface
I am so tired, really tired. The company’s project has been going on for a long time, and there are still problems up to now. As a result, there has been no text output for two or three months. In fact, this is an excuse, the key or lazy, last weekend also went out to play a 😂.
It’s been a few months since Compose’s stable release, and I’ve been surprised by the fact that the forums for Compose have been buzzing since the alpha and beta releases, and a bunch of articles have been posted, but not since the official release.
But that’s just the state of the art in tech forums, where the big guys are still making progress. For example, Lottie, Compose, has been adapting its official version for a while now. Of course, there are still many libraries in Compose that have not been adapted, but there is no need to worry, it will be soon, the current adaptation is probably enough, and a few that are not available can also be used through AndroidView.
The body of the preparation
First of all, people use Lotties all the time, so what is lotties? Take a look at the introduction on the official website:
Lottie is a library for Android, iOS, Web, and Windows that parses Adobe After Effects animations exported as JSON using Bodymovin and renders them natively on mobile devices and the Web!
If you want to use Lottie to play animations in Android, you first need a JSON animation. If you do not have an animation file, you need to play a Der.
So where do I find the JSON-formatted animations used in Lottie? The simplest way is to find a design!
What? Design says no? Go out and turn right!
Instead, I’ll give you a site to download the JSON-formatted animations used in Lottie:
lottiefiles.com/
In this website you can search the animation you want to download, create an account can download for free, how to download here is not posted tutorial, we should be better than I will play.
After downloading, place the downloaded files in the raw folder of the project. If there is no raw folder, create a raw folder under the RES file and put the downloaded animation files in it.
OK, all ready!
Awkward text
Above said a bunch of nonsense, we don’t be bored, haven’t written an article for a long time, a little strange… Now begin the body of the day.
Add the dependent
First add Lottie dependencies in the module’s build.gradle file:
dependencies {
...
implementation "com.airbnb.android:lottie-compose:$lottieVersion"
...
}
Copy the code
One of thelottieVersion
为 Lottie
As OF this writing, the latest version is 4.2.0. If you want to use the latest version, please replace the version number withAnd this isLottie
The latest version of the.
Since Lottie is hosted in a Sonatype repository, you also need to add a Sonatype repository to your project’s build.gradle file:
allprojects {
repositories {
...
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
}
Copy the code
Now that Lottie’s dependencies are added, let’s start with how to use them.
Simple to use
Let’s take a look at the usage code:
@Composable
fun SystemPage() {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.weather_rain))
val progress by animateLottieCompositionAsState(composition)
LottieAnimation(composition = composition, progress = progress)
}
Copy the code
The first line loads the animation file, the second line converts the animation file into a State file suitable for use in Compose, and the third line puts the animation file and State file into LottieAnimation. This is how Lottie is used in Compose.
That should have been the end of the article. End what? What did you say? They don’t have a? What is the implementation style? How to implement a more complicated one? Did you? Did you??)
Ha ha ha, run to see the effect below!
Because it is virtual machine operation, so look at a little card, the real machine effect is very smooth, just like Dove!
The source code parsing
After the above code is written, we will find some problems. For example, we may want to play continuously, but the animation stops after playing once, which is not what we want. What if we want to control the speed of the animation? Wait, this time we need to take a look at Lottie source to find the answer!
Loading an animation file
First let’s look at the definition of how to load an animation file:
@Composable
fun rememberLottieComposition(
spec: LottieCompositionSpec,
imageAssetsFolder: String? = null,
fontAssetsFolder: String = "fonts/",
fontFileExtension: String = ".ttf",
cacheKey: String? = DefaultCacheKey,
onRetry: suspend (failCount: Int, previousException: Throwable) -> Boolean = { _, _ -> false },
)
Copy the code
Can see rememberLottieComposition function were six parameters, only the spec is must fill in the rest of the five parameters are required, the following let’s look at each of these six parameters is why use!
- spec: defines which should be loaded
LottieComposition
.LottieComposition
Is the animation file we are going to load, which will be explained in the following content; - imageAssetsFolder:
src/main/assets
Contains the exported images used for this composition; - fontAssetsFolder:
Lottie
Will look for font files in the default folder. Fonts will be matched according to the series names specified in the Lottie JSON file. The default value is “Fonts”; - fontFileExtensionIn:
fontAssetsFolder
或fontRemapping
The default file extension for the font file specified in the. - cacheKey: Sets the cache key so that subsequent calls will be returned directly from the cache without having to reload and parse the animation, if set to NULL to skip the cache. By default, from
LottieCompositionSpec
Automatically generate a derived cache key; - OnRetry: This is an optional callback that will be called if the animation fails to load, with two arguments passing the count of failed attempts and the exception of the last attempt to load the combination.
LottieCompositionSpec is the most commonly used parameter, and is retry on spec. LottieCompositionSpec is the required parameter.
Sealed interface LottieCompositionSpec {/ * * * * loading animation from the res/raw/inline class RawRes (@ androidx. The annotation. RawRes val ResId: Int) : LottieCompositionSpec /** * Loading animation from Internet */ Inline class Url(val Url: String) : LottieCompositionSpec /** * Load animation from File */ Inline class File(val fileName: String) : LottieCompositionSpec /** * Load animation from Asset */ Inline class Asset(val assetName: String) : LottieCompositionSpec /** * loads the animation from its JSON string. */ inline class JsonString(val jsonString: String) : LottieCompositionSpec }Copy the code
LottieCompositionSpec is an interface that has five classes that implement it. It can be called directly from the constructor. You can load an animation file in a project, a network file, or a string. This greatly improves the use of comfort, the following to see the use of it!
val composition1 by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.weather_rain)) val composition2 by RememberLottieComposition (LottieCompositionSpec. Url (" animation files site ")) val composition3 by RememberLottieComposition (LottieCompositionSpec File (" File name ")) val composition4 by RememberLottieComposition (LottieCompositionSpec. Asset (" file ")) val composition5 by RememberLottieComposition (LottieCompositionSpec JsonString (" animation json string "))Copy the code
Isn’t it very simple?
Set animation Progress
Now that the animation file is created, let’s look at the animation progress State method definition:
@Composable fun animateLottieCompositionAsState( composition: LottieComposition? , isPlaying: Boolean = true, restartOnPlay: Boolean = true, clipSpec: LottieClipSpec? = null, speed: Float = 1f, iterations: Int = 1, cancellationBehavior: LottieCancellationBehavior = LottieCancellationBehavior.Immediately, )Copy the code
As you can see, animateLottieCompositionAsState function has a total of seven parameters, which is only one parameter for must function, LottieComposition is we just created, the rest of the six parameters are essential functions, Let’s look at how each parameter is used:
- IsPlaying: Indicates whether the animation is currently playing. Note that the animation may end when the target number of iterations is reached. If this happens, the animation may stop even if this parameter is set to true;
- RestartOnPlay: If isPlaying is switched from False to true, restartOnPlay is used to determine whether to reset progress and iterate;
- ClipSpec: Specifies the boundary to which animation playback should be clipped (this parameter is not covered in this article);
- Speed: The speed at which the animation should play. If it is greater than 1 it speeds up, if it is between 0 and 1 it slows down, and if it is less than 0 it moves backwards.
- iterations: Number of times the animation should be repeated before stopping (a positive integer), set to if you want to repeat forever
LottieConstants.IterateForever
.LottieConstants.IterateForever
In fact, isInteger.MAX_VALUE
; - cancellationBehavior: The behavior of an animation when it is cancelled, can be set to if there is a state-based transition and you want to finish playing before moving on to the next animation
LottieCancellationBehavior.OnIterationFinish
.
As you see here, the two issues we just raised have been solved. You can change the playback speed of animations by setting speed and iterations to modify the playback times of animations. Here’s how to use it:
val progress by animateLottieCompositionAsState( composition = composition, speed = 2f, / / speed up the play (double speed) iterations = LottieConstants. IterateForever / / set never end)Copy the code
In the code above, I set the playback speed to double and never finish. Here’s how it works:
You can see that the animation is much faster and looping, which is where we want it to be.
Lottie animation control
The Lottie animation control is a Lottie animation control. The Lottie animation control is a Lottie animation control.
@Composable fun LottieAnimation( composition: LottieComposition? , @floatrange (from = 0.0, to = 1.0) progress: Float, modifier: modifier = modifier, outlineMasksAndMattes: Float Boolean = false, applyOpacityToLayers: Boolean = false, enableMergePaths: Boolean = false, dynamicProperties: LottieDynamicProperties? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, )Copy the code
It can be seen that LottieAnimation has a total of nine parameters, two of which are required, namely the animation file and animation progress mentioned above. The remaining seven parameters are optional. Let’s have a look at them in detail:
- Modifier: a platitudes modifier, can set the width and height of the control, etc., but more introduction;
- OutlineMasksAndMattes: Enable this option to debug slow motion paintings by overview masks and masks. The performance overhead of masks and masks is proportional to the surface area of all mask combinations. Caution: Never enable this feature in the official version;
- ApplyOpacityToLayers: Sets whether to apply opacity to each layer instead of the shape. Opacity is usually applied directly to shapes. In cases where translucent shapes overlap, applying opacity to layers is more accurate, but at the expense of performance;
- EnableMergePaths: Enable experimental merge paths support. Most animations with merge paths want this enabled, but merge paths support is more limited than some other rendering features, so it is turned off by default;
- dynamicProperties: Allows dynamic changes to animation properties that can be passed
rememberLottieDynamicProperties
To use (the description is not expanded in this article); - Alignment: Defines where the animation should be placed in this composable object if the size of the animation is different from the size of this composable item;
- ContentScale: Defines how the animation should be scaled if the size of the animation is different from this or this composable item.
You can choose the parameters according to the requirements of the actual project.
Snap ending
This article is pretty simple, just showing you how Lottie is used in Compose.
Let me know in the comments section if you have any questions about this article.
Don’t forget to like and follow this article if it helps you. Thank you 🙏.