引言
上周周会了解到Lottie这个开源项目,用json文件控制播放动画,跟我之前做主题,用cocos-2dx引擎做游戏动画思想有些类似,当时我就想体验一下这个项目。
初识Lottie
首先看一组效果图:
感觉上面这个效果挺赞的,通过动作分解,也能用Android提供的位移、旋转、透明动画组合,配合一些Interpolator(加速、减速、弹跳)来实现;但是下面这个用上面的方法进行动画控制就太麻烦了(从效果看出,下面的图形都不是通过图片控制的,全部都是通过path绘制的),当前也可以通过gif动画来播放,不过gif动画在低端手机可能会出现不流畅现象,再者就是gif图片size较大,对包体大小有限制的App可能就不能接受:
Lottie介绍
介绍
Today, we’re happy to introduce our solution. Lottie is an iOS, Android, and React Native library that renders After Effects animations in real time, and allows native apps to use animations as easily as they use static assets. Lottie uses animation data exported as JSON files from an open-source After Effects extension called Bodymovin. The extension is bundled with a JavaScript player that can render the animations on the web. Since February of 2015, Bodymovin’s creator, Hernan Torrisi, has built a solid foundation by adding features and improvements to the plugin on a monthly basis. Our team (Brandon Withrow on iOS, Gabriel Peal on Android, Leland Richardson on React Native, and I on experience design) began our journey by building on top of Torrisi’s phenomenal work.
就是说Lottie支持Android、iOS、React Native三个平台,支持实时渲染After Effects动画,使得app中使用动画可以像使用静态资源一样简单。 Lottie使用从Bodymovin(开源的After Effects插件)导出的json数据来作为动画数据。
源码分析
github上下载lottie-android源码,导入AS,容易找到加载本地的动画json文件入口方法:
void onLoadAssetClicked() {
animationView.cancelAnimation();
android.support.v4.app.DialogFragment assetFragment = ChooseAssetDialogFragment.newInstance();
assetFragment.setTargetFragment(this, RC_ASSET);
assetFragment.show(getFragmentManager(), "assets");
}
Lottie支持从本地加载json文件来实现,也支持从网络加载json格式的动画数据来实现播放动画(原理一样)。加载完成后,会通过下面函数对动画进行处理:
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case RC_ASSET:
final String assetName = data.getStringExtra(EXTRA_ANIMATION_NAME);
animationView.setImageAssetsFolder(assetFolders.get(assetName));
LottieComposition.Factory.fromAssetFileName(getContext(), assetName,
new OnCompositionLoadedListener() {
@Override
public void onCompositionLoaded(LottieComposition composition) {
setComposition(composition, assetName);
}
});
break;
case RC_FILE:
onFileLoaded(data.getData());
break;
case RC_URL:
break;
}
}
其中最核心的方法就是setComposition(composition, assetName),这个方法最核心的一句是animationView.setComposition(composition);下面看一下这个方法的实现:
/**
* Sets a composition.
* You can set a default cache strategy if this view was inflated with xml by
* using {@link R.attr#lottie_cacheStrategy}.
*/
public void setComposition(@NonNull LottieComposition composition) {
if (L.DBG) {
Log.v(TAG, "Set Composition \n" + composition);
}
lottieDrawable.setCallback(this);
boolean isNewComposition = lottieDrawable.setComposition(composition);
if (!isNewComposition) {
// We can avoid re-setting the drawable, and invalidating the view, since the composition
// hasn't changed.
return;
}
int screenWidth = Utils.getScreenWidth(getContext());
int screenHeight = Utils.getScreenHeight(getContext());
int compWidth = composition.getBounds().width();
int compHeight = composition.getBounds().height();
if (compWidth > screenWidth ||
compHeight > screenHeight) {
float xScale = screenWidth / (float) compWidth;
float yScale = screenHeight / (float) compHeight;
setScale(Math.min(xScale, yScale));
Log.w(L.TAG, String.format(
"Composition larger than the screen %dx%d vs %dx%d. Scaling down.",
compWidth, compHeight, screenWidth, screenHeight));
}
// If you set a different composition on the view, the bounds will not update unless
// the drawable is different than the original.
setImageDrawable(null);
setImageDrawable(lottieDrawable);
this.composition = composition;
requestLayout();
}
可以看到,通过composition的设置和请求requestLayout刷新界面,即可实现动画的绘制,那么究竟composition和lottieDrawable是什么关系?以及他们是怎么实现动画的绘制的?下面通过类图来表达这一它们之间的关系:
看起来比较复杂的动画逻辑,其实实现起来并不是特别复杂,他们之间的关系很清晰:LottieAnimationView继承AppCompatImageView,即可以当做一个增强版的ImageView来使用,只不过它里面包含了两个核心成员:LottieDrawable和LottieComposition,所有的动画播放和完成,都是通过控制这两个核心成员来完成的。
LottieComposition
负责解析Effects/Bodymovin产生的json动画文件,并将其按照功能分类保存起来。可以这样理解:LottieComposition就是动画json数据的对象模型,通过LottieComposition,实现对动画的分解和序列化,json动画文件示例:
LottieDrawable
LottieDrawable就是根据LottieComposition保存的分层和序列动作,不停的进行绘制,实现连续动画效果,其核心逻辑如下:
@Override public void draw(@NonNull Canvas canvas) {
if (compositionLayer == null) {
return;
}
matrix.reset();
matrix.preScale(scale, scale);
compositionLayer.draw(canvas, matrix, alpha);
}
真正的实现在CompositionLayer的draw函数,即:
@Override
public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (!visible) {
return;
}
buildParentLayerListIfNeeded();
matrix.reset();
matrix.set(parentMatrix);
for (int i = parentLayers.size() - 1; i >= 0; i--) {
matrix.preConcat(parentLayers.get(i).transform.getMatrix());
}
int alpha = (int)
((parentAlpha / 255f * (float) transform.getOpacity().getValue() / 100f) * 255);
if (!hasMatteOnThisLayer() && !hasMasksOnThisLayer()) {
matrix.preConcat(transform.getMatrix());
drawLayer(canvas, matrix, alpha);
return;
}
rect.set(0, 0, 0, 0);
getBounds(rect, matrix);
intersectBoundsWithMatte(rect, matrix);
matrix.preConcat(transform.getMatrix());
intersectBoundsWithMask(rect, matrix);
rect.set(0, 0, canvas.getWidth(), canvas.getHeight());
canvas.saveLayer(rect, contentPaint, Canvas.ALL_SAVE_FLAG);
// Clear the off screen buffer. This is necessary for some phones.
clearCanvas(canvas);
drawLayer(canvas, matrix, alpha);
if (hasMasksOnThisLayer()) {
applyMasks(canvas, matrix);
}
if (hasMatteOnThisLayer()) {
canvas.saveLayer(rect, mattePaint, SAVE_FLAGS);
clearCanvas(canvas);
//noinspection ConstantConditions
matteLayer.draw(canvas, parentMatrix, alpha);
canvas.restore();
}
canvas.restore();
}
小结
真心觉得这个项目实在是太赞了,倒不是说这个项目在技术上有多高深,而是这个项目把软件开发(或者说是编码实现需求)的方法想得很极致:不是通过复杂的组合动画和波动函数来控制,而是通过对数据建模,通过设计师导出的数据,在不同平台上还原出效果,完成设计稿与实现效果的完全还原(如果是通过系统动画,很多情况下难以完全符合设计师的动画要求)
- 有了lottie,设计师再也不用担心开发不能达到预期效果了,因为压根不需要额外开发
- 解放了开发,启迪了思想,我还需要学习一个!
参考文章
https://github.com/airbnb/lottie-android
https://medium.com/airbnb-engineerin
http://www.jianshu.com/p/d887c96684be