关键代码如下:
var builder = Fresco.newDraweeControllerBuilder()
//需要设置true ,gif才能 播放,但是其实会有一个问题,在activity重新回到可见状态后,gif又会被重新执行一遍
.setAutoPlayAnimations(true)
//设置uri,加载本地的gif资源,gif 代表gif文件资资源id
.setUri(Uri.parse("res://" + context.packageName + "/" + gif))//设置uri
//进行监听
.setControllerListener(object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
// log.e("image final set")
if (animatable != null && !animatable.isRunning) {
// log.e("start animatable")
animatable.start()
val animatedDrawable2 = animatable as AnimatedDrawable2
//设置gif的播放次数关键位置,
animatedDrawable2.animationBackend = LoopCountBackend(animatedDrawable2.animationBackend!!, 1)
//这里为gif的播放监听
animatedDrawable2.setAnimationListener(object : AnimationListener {
override fun onAnimationRepeat(drawable: AnimatedDrawable2?) {
// log.e("test animation repeat")
}
override fun onAnimationStart(drawable: AnimatedDrawable2?) {
// log.e("test animation onAnimationStart")
}
override fun onAnimationFrame(drawable: AnimatedDrawable2?, frameNumber: Int) {
// log.e("test animation onAnimationFrame")
}
override fun onAnimationStop(drawable: AnimatedDrawable2?) {
// log.e("test animation onAnimationStop")
// drawable?.isAutoMirrored=false
// animatable.stop()
//如果加这行代码的话,在activity重新resume后gif动画不会再被播放一次
// animation.controller?.onDetach()
//这里的意思是在gif播放完结束后重新设置一张图片,实际效果可能是在gif播放完后会闪一下,但是能解决activity重新回到界面上后又重新播放的问题
UIHelper.getInstance().setImg("res://" + context.packageName + "/" + check_resource, animation)
}
override fun onAnimationReset(drawable: AnimatedDrawable2?) {
// log.e("test animation onAnimationReset")
}
})
}
}
})
var mDraweeController = builder.build()
animation.setController(mDraweeController)
/**
* fresco 动画播放的设置类
*/
class LoopCountBackend : AnimationBackendDelegate<AnimationBackend> {
//这里代表播放的次数,可以设置
var mLoopCount: Int = 1
constructor(@Nullable animationBackend: AnimationBackend, loopCount: Int) : super(animationBackend) {
mLoopCount = loopCount
}
override fun getLoopCount(): Int {
return mLoopCount
}
}