来自 XML
最简单的方法是像使用普通 ImageView 一样使用 GifImageView(或 GifImageButton):
<pl.droidsonroids.gif.GifImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/src_anim"
android:background="@drawable/bg_anim"
/>
如果 android:src 和/或 android:background 声明的 drawables 是 GIF 文件,那么它们将被自动识别为 GifDrawables 并具有动画效果。如果给定的 drawable 不是 GIF,那么提到的 View 就像普通的 ImageView 和 ImageButton 一样工作。
GifTextView 允许您将 GIF 用作复合可绘制对象和背景。
<pl.droidsonroids.gif.GifTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableTop="@drawable/left_anim"
android:drawableStart="@drawable/left_anim"
android:background="@drawable/bg_anim"
/>
来自 Java 代码
GifImageView、GifImageButton 和 GifTextView 也实现了 setter 的钩子。所以可以通过调用setImageResource(int resId)和setBackgroundResource(int resId)来设置动画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 );
如果不再需要 GifDrawable,InputStream 会在终结器中自动关闭,因此您无需显式关闭它们。调用recycle() 也会关闭底层输入源。
请注意,所有输入源都需要能够倒回到开头。需要正确播放动画 GIF(动画是可重复的),因为后续帧是根据需要从源解码的。
参考:https://github.com/koral--/android-gif-drawable