Android 实现Gif播放的七种方法

背景:在项目里某个需求实现的时候,有个图标有一个动画效果,为了达到UI要求的效果,试过多种方案,在这篇文章中讲一下这些方案的用法,以及结合项目的现状,做的一个方案选择。

1. Glide

Link:https://github.com/bumptech/glide
Glide是Android上比较常见的图片加载框架了,在Android上是数一数二的图片加载框架代表了,当然,早期的类似ImageLoaderPicasso这些,算是比较具有历史性的图片加载框架了。

Glide加载Gif的话,用到的是GifDrawable这个对象,一般我们用

Glide.with(fragment)
  .asGif()
  .load(url)
  .into(new SimpleTarget<>() {
    @Override
    public void onResourceReady(GifDrawable resource, Transition transition) {
      resource.start();
      // Set the resource wherever you need to use it.
    }
  });

去创建,当然,如果你加载的是 Bitmap 或 GifDrawable,你可以判断这个可绘制对象是否实现了 Animatable:

Glide.with(fragment)
  .load(url)
  .into(new SimpleTarget<>() {
    @Override
    public void onResourceReady(Drawable resource, Transition transition) {
      if (resource instanceof Animatable) {
        resource.start();
      }
      // Set the resource wherever you need to use it.
    }
  });

动画控制

  • setLoopCount(int loopCount) - 控制gif的播放次数
  • registerAnimationCallback(@NonNull AnimationCallback animationCallback) - 控制播放回调
  • isRunning() - 动画是否正在运行中
  • stop() - 停止动画

!!#38761d 注意:查看源码发现Glide内部是没有调用onAnimationStart,只调用了onAnimationEnd,故如果要监听在动画开始之前需要做什么操作的话,建议在调用start()之前手动去做;!!

2. android-gif-drawable

Link:https://github.com/koral--/android-gif-drawable
android-gif-drawable也是Android上比较火热的图片加载框架

这个库播放Gif用到的也是pl.droidsonroids.gif.GifDrawableGifDrawable对象,不像Glide,它的创建的方式比较简单

//resource (drawable or raw)
val d = pl.droidsonroids.gif.GifDrawable(context.resources,R.mipmap.ic_jizhi_hello)

//asset file
GifDrawable gifFromAssets = new GifDrawable( getAssets(), "anim.gif" );

//FileDescriptor
FileDescriptor fd = new RandomAccessFile( "/path/anim.gif", "r" ).getFD();
GifDrawable gifFromFd = new GifDrawable( fd );

//file path
GifDrawable gifFromPath = new GifDrawable( "/path/anim.gif" );

可以根据需求,选择不同的构造器创建对象

动画控制

GifDrawable 实现了 AnimatableMediaPlayerControl 接口,所以你可以使用他们各自的方法甚至更多

  • stop() - 停止动画, 可以在任意线程调用
  • start() - 开启动画, 可以在任意线程调用
  • isRunning() - 返回当前动画是否正在运行中
  • reset() - rewinds the animation, does not restart stopped one
  • setSpeed(float factor) - 设置动画的倍速 举例. 传入2.0f 将会以2倍速播放
  • seekTo(int position) - 移动动画到 (within current loop) 指定的 position (in milliseconds)
  • getDuration() - 返回动画一次的完整时长
  • getCurrentPosition() - 返回动画当前的位置
  • setLoopCount(int loopCount) - 控制gif的播放次数

使用 MediaPlayerControl
MediaPlayer的标准控件(如VideoView)可用于控制GIF动画并显示其当前进度。
只需在MediaController上将GifDrawable设置为MediaPlayer,如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GifImageButton gib = new GifImageButton(this);
    setContentView(gib);
    gib.setImageResource(R.drawable.sample);
    final MediaController mc = new MediaController(this);
    mc.setMediaPlayer((GifDrawable) gib.getDrawable());
    mc.setAnchorView(gib);
    gib.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mc.show();
        }
   });
}

更多详细用法见 Github Usage

bug:isRunning always return true
Currently it is not possible to check directly if animation is finished. Indirect way is to register animation listener.
issues_129

3. AnimatedImageDrawable

Link:android.jar-android.graphics.drawable
AnimatedImageDrawable是Android官方推出播放动图的类,优点是官方稳定高效,缺点是仅支持Android P版本(api=28)以上

使用方法也比较简单

val source = ImageDecoder.createSource(context.resources, R.mipmap.ic_jizhi_hello)
ImageDecoder.decodeDrawable(source).apply {
    if (this is AnimatedImageDrawable) {
        repeatCount = 0
        registerAnimationCallback(object : Animatable2.AnimationCallback() {
            override fun onAnimationStart(drawable: Drawable?) {
                super.onAnimationStart(drawable)
            }
            
            override fun onAnimationEnd(drawable: Drawable?) {
                super.onAnimationEnd(drawable)
            }
        })
        animateImageDrawable = this
    }
}
imageView.setImageDrawable(animateImageDrawable)
animateImageDrawable.start()

动画控制

  • setRepeatCount(@IntRange(from = REPEAT_INFINITE) int repeatCount) - 控制gif的播放次数
  • isRunning() - 动画是否正在运行中
  • stop() - 停止动画
  • registerAnimationCallback(@NonNull AnimationCallback callback) - 动画回调

Notice: AnimatedImageDrawable要求API必须高于android P(28),那么在api低于28的时候,有没有比较好的方法呢?答案肯定是有的,往下看Movie。

4. Movie

Link:android.jar-android.graphics
android.graphics.Movie 也是Android自带的类,可以用来加载播放Gif动画,实现起来相对来说可能比较繁琐,官方已经将这个类标记为 @Deprecated {@link android.graphics.drawable.AnimatedImageDrawable},但还是有必要讲下。
主要的构造方法有:

Movie decodeStream(InputStream is)
Movie decodeFile(String pathName)
Movie decodeByteArray(byte[] data, int offset,int length)

按来源分别可以从Gif文件的输入流,文件路径,字节数组中得到Movie的实列。然后我们可以通过操作Movie对象来操作Gif文件。
下面介绍下几个方法:

  • int width() movie的宽,值等于gif图片的宽,单位:px。
  • int height() movie的高,值等于gif图片的高,单位:px。
  • int duration() movie播放一次的时长,也就是gif播放一次的时长,单位:毫秒。
  • boolean isOpaque() Gif图片是否带透明
  • boolean setTime(int relativeMilliseconds) 设置movie当前处在什么时间,然后找到对应时间的图片帧,范围0 ~ duration。返回是否成功找到那一帧。
  • draw(Canvas canvas, float , float y)
  • draw(Canvas canvas, float x, float y, Paint paint)
    在Canves中画出当前帧对应的图像。x,y对应Movie左上角在Canves中的坐标。

关键是Movie官方没有给出回调监听,故我们需要手动做监听。
有兴趣的可以看这一篇文章,写的很不错。Android自定义View播放Gif动画

5. Lottie

当然,除了这些之外,还有跨平台的解决方案,比起传统的gif文件,Lottie则是使用json文件来代表动画源文件。

Lottie对APK的影响有多大?

  • ~1600 方法.
  • 287kb 未压缩.

Add the dependency to your project build.gradle file:

dependencies {
    implementation "com.airbnb.android:lottie:$lottieVersion"
}

核心类:

  • LottieAnimationView - 继承自ImageView,简单以默认的形式去加载Lottie动画.
  • LottieDrawable - 跟LottieAnimationView的APIs大部分相同,但是你可以使用它在你任何想要使用的view上.
  • LottieComposition - is the stateless model representation of an animation. This file is safe to cache for as long as you need and can be freely reused across drawables/views.
  • LottieCompositionFactory - allows you to create a LottieComposition from a number of inputs. This is what the setAnimation(...) APIs on LottieDrawable and LottieAnimationView use under the hood. The factory methods share the same cache with those classes as well.

加载动画:
Lottie可以加载动画来自:

  • src/main/res/raw 中的 json 动画.
  • src/main/assets 中的 json 文件.
  • src/main/assets中的 zip 文件 . See images docs for more info.
  • src/main/assets 中的一个dotLottie 文件.
  • 指向一个 json or zip 文件的url.
  • 一个json字符串,可以是任意形式的来源,包括你的网络栈.
  • json 文件或者一个 zip 文件的输入流.

From XML

最简单的形式就是使用LottieAnimationView
推荐使用 lottie_rawRes ,相对于使用指定的字符串文件名,你可以使用通过 R 文件以静态的引用形式指定你的动画文件.

From res/raw ( lottie_rawRes ) or assets/ ( lottie_fileName )


动画监听

animationView.addAnimatorUpdateListener { animation ->
}
animationView.addAnimatorListener(...)
animationView.addPauseListener {
}

更多详细介绍及用法见官方文档

6. FrameSequenceDrawable

Link:https://android.googlesource.com/platform/frameworks/ex/+/android-5.0.2_r1/framesequence
FrameSequenceDrawable更多的是对webp格式的一个支持,所以当要使用时,需要将你的gif转为webp

涉及到的类

  • FrameSequenceDrawable
    这个我们直接使用播放webp动画的类,它继承了Drawable并且实现了Animatable, Runnable两个接口,所以我们可以像使用Drawable一样的去使用它

  • FrameSequence
    从名字上来看这个类的意思很明确,那就是帧序列,它主要负责对传入的webp流进行解析,解析的地方是在native层,所以如果自己想编译FrameSequenceDrawable源码的话,需要编译JNI文件夹下的相关文件生成so库

来看下主要的构造方法:

decodeByteArray(byte[] data)
decodeByteArray(byte[] data, int offset, int length)
decodeByteBuffer(ByteBuffer buffer)
decodeStream(InputStream stream)

使用方法如下:

val input = context.assets.open("ic_jizhi_hello_webp.webp")
val fsd = FrameSequenceDrawable(FrameSequence.decodeStream(input))

or

val bitmap = BitmapFactory.decodeResource(context.resources, R.mipmap.ic_jizhi_hello_webp)
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.WEBP, 100, stream)
val imageInByte = stream.toByteArray()
val fsd = FrameSequenceDrawable(
    FrameSequence.decodeStream(ByteArrayInputStream(imageInByte))
)

imageView.setImageDrawable(fsd)
  • setLoopCount(int loopCount) - 控制播放次数
  • setLoopBehavior(int loopBehavior) - Must be one of LOOP_ONCE, LOOP_INF, LOOP_DEFAULT, or LOOP_FINITE.
  • setOnFinishedListener(OnFinishedListener onFinishedListener) - 注册播放完毕回调
  • isRunning() - 动画是否正在运行中
  • stop() - 停止动画

注意:
1 - 使用FrameSequenceDrawable的时候,必须手动拷贝FrameSequenceFrameSequenceDrawable两个文件
放在项目app下 android.support.rastermill 目录
2 - jni文件见目录 /jni
3 - 顺便说一句:我是不知道怎么编译,有知道怎么弄的小伙伴请多多指教 :)

最后

[Facebook/Fresco](https://github.com/facebook/fresco) 也支持gif的加载,大同小异,这里就不再过多介绍了。

Glide在部分设备上遇到了Gif变慢的问题,详见 issues_2471
考虑到项目已经集成了Glide了,就不打算再继续引入第三方的库了。又因为原素材的问题,无法导出Lottie格式的json文件。
故这一块当时做的就是 >=androidP 用AnimatedImageDrawable,

你可能感兴趣的:(Android 实现Gif播放的七种方法)