android上面进行gif动画播放,稍稍大点的动画,播放时候,总出现内存溢出。下面这个库将很大程度上解决你的问题,
android-gif-drawable是通过jni进行渲染的,非常高效。
github:https://github.com/koral--/android-gif-drawable
使用方法也比较简单
依赖
在你的build.gradle加入依赖
dependencies {
compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.15'
}
布局
在你的xml布局中加入GIF控件,用法与ImageView差不多,src与background都是支持gif动画的
<pl.droidsonroids.gif.GifImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/src_anim"
android:background="@drawable/bg_anim"
/>
另外还有GifImageButton,GifTextView等控件,用法分别类似ImageButton,TextView,支持drawable属性的都支持gif啦。
代码操作
首先创建GifDrawable。
//asset file
GifDrawable gifFromAssets = new GifDrawable( getAssets(), "anim.gif" );
//resource (drawable or raw)
GifDrawable gifFromResource = new GifDrawable( getResources(), R.drawable.anim );
//byte array
byte[] rawGifBytes = ...
GifDrawable gifFromBytes = new GifDrawable( rawGifBytes );
//FileDescriptor
FileDescriptor fd = new RandomAccessFile( "/path/anim.gif", "r" ).getFD();
GifDrawable gifFromFd = new GifDrawable( fd );
//file path
GifDrawable gifFromPath = new GifDrawable( "/path/anim.gif" );
//file
File gifFile = new File(getFilesDir(),"anim.gif");
GifDrawable gifFromFile = new GifDrawable(gifFile);
//AssetFileDescriptor
AssetFileDescriptor afd = getAssets().openFd( "anim.gif" );
GifDrawable gifFromAfd = new GifDrawable( afd );
//InputStream (it must support marking)
InputStream sourceIs = ...
BufferedInputStream bis = new BufferedInputStream( sourceIs, GIF_LENGTH );
GifDrawable gifFromStream = new GifDrawable( bis );
//direct ByteBuffer
ByteBuffer rawGifBytes = ...
GifDrawable gifFromBytes = new GifDrawable( rawGifBytes );
通过setImageDrawable()展示出来。
另外我们需要控制gif播放,例如播放暂停等,可直接用GifDrawable 。还可以设置监听,GifDrawable 。addAnimationListener。注意啊是GifDrawable ,不是GifImageView。
另外
当一个页面有多个GifImageView播放东一个GifDrawable,注意使用MultiCallback
MultiCallback multiCallback = new MultiCallback();
imageView.setImageDrawable(gifDrawable);
multiCallback.addView(imageView);
anotherImageView.setImageDrawable(gifDrawable);
multiCallback.addView(anotherImageView);
gifDrawable.setCallback(multiCallback);