社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
目前支持Gif播放的开源库还是有的,试了一下还是这种好用点,所以来分享下
android-gif-drawable是通过JNI来渲染帧的,这种方式比使用WebView或者Movie效率要高
要求
Android 4.2+(API级别17+)
用于GifTextureView硬件加速渲染
适用于GifTexImage2DOpenGL ES 2.0+
效果图:
GifDrawable 可以直接从各种来源构建:
//资产文件
GifDrawable gifFromAssets = new GifDrawable(getAssets(), “ anim.gif ”);
//资源(可拉伸或原始)
GifDrawable gifFromResource = 新 GifDrawable(getResources(), - [R 。可拉伸。阿尼姆);
// Uri
ContentResolver contentResolver = ... //对于file可以为null:// Uris
GifDrawable gifFromUri = new GifDrawable(contentResolver,gifUri);
// byte array
byte [] rawGifBytes = ...
GifDrawable gifFromBytes = new GifDrawable(rawGifBytes);
// FileDescriptor
FileDescriptor fd = new RandomAccessFile( “/ path/anim.gif ”, “ r ”)。getFD();
GifDrawable gifFromFd = new GifDrawable(fd);
//文件路径
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(必须支持标记)
InputStream sourceIs = ...
BufferedInputStream bis = new BufferedInputStream(sourceIs, GIF_LENGTH);
GifDrawable gifFromStream = new GifDrawable(bis);
// direct ByteBuffer
ByteBuffer rawGifBytes = ...
GifDrawable gifFromBytes = new GifDrawable(rawGifBytes);
效果图代码:
<pl.droidsonroids.gif.GifImageView
android:id="@+id/gif_image_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@mipmap/gif1" />
GifImageView gifImageView1= findViewById(R.id.gif_image_view1);
File file = new File("/storage/emulated/0/Android/data/com.zhangqie.gif/cache/thumb/SpiderDressUp.gif");
try {
//file方式
//GifDrawable gifFromPath = new GifDrawable(file);
//直接给地址
GifDrawable gifFromPath = new GifDrawable("/storage/emulated/0/Android/data/com.zhangqie.gif/cache/thumb/SpiderDressUp.gif");
gifImageView1.setImageDrawable(gifFromPath);
} catch (IOException e) {
e.printStackTrace();
}
/*gifDrawable.start(); //开始播放
gifDrawable.stop(); //停止播放
gifDrawable.reset(); //复位,重新开始播放
gifDrawable.isRunning(); //是否正在播放
gifDrawable.setLoopCount( 2 ); //设置播放的次数,播放完了就自动停止
gifDrawable.getCurrentLoop(); //获取正在播放的次数
gifDrawable.getCurrentPosition() ; //获取现在到从开始播放所经历的时间
gifDrawable.getDuration() ; //获取播放一次所需要的时间
gifDrawable.recycle();//释放内存*/
点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
gifDrawable.stop();
break;
case R.id.btn2:
gifDrawable.start();
break;
}
}
代码文档:https://github.com/koral--/android-gif-drawable
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!