效果图:
实现步骤,注释已经在代码中详细给出:
1.布局activity_gif.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".GifActivity"> <ImageView android:id="@+id/img_gif" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
2.GifActivity代码如下:
public class GifActivity extends AppCompatActivity { private ImageView img_gif; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gif); img_gif = findViewById(R.id.img_gif); //如果系统版本为Android9.0以上,则利用新增的AnimatedImageDrawable显示GIF动画 if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.P){ showGifAnimationNew(); }else { showGifAnimationOld();//显示GIF动画 } } private void showGifAnimationNew() { if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.P){ try { //利用Android9.0新增的ImageDecoder读取gif动画 ImageDecoder.Source source = ImageDecoder.createSource(getResources(), R.drawable.welcome); //从数据源中解码得到gif图形数据 Drawable drawable = ImageDecoder.decodeDrawable(source); //设置图像视图的图形为gif图片 img_gif.setImageDrawable(drawable); //如果是动画图形,则开始播放动画 if (drawable instanceof Animatable){ ((Animatable)img_gif.getDrawable()).start(); } }catch (Exception e){ e.printStackTrace(); } } } //显示GIF动画 private void showGifAnimationOld() { //从资源文件welcome.gif中获取输入流对象 InputStream is = getResources().openRawResource(R.raw.welcome); //创建一个GIF图像对象 GifImage gifImage = new GifImage(); //从输入流中读取gif数据 int code = gifImage.read(is); if (code == GifImage.STATUS_OK){ //读取成功 GifImage.GifFrame[] frames = gifImage.getFrames(); //创建一个帧动画 AnimationDrawable animationDrawable = new AnimationDrawable(); for (GifImage.GifFrame f:frames){ //把Bitmap位图对象转换为Drawable图像格式 BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),f.image); //给帧动画添加指定图形,以及该帧的播放延迟 animationDrawable.addFrame(bitmapDrawable,f.delay); } //设置帧动画是否播放一次 true:表示播放一次 false:表示循环播放 animationDrawable.setOneShot(false); //设置图像视图的图形为帧动画 img_gif.setImageDrawable(animationDrawable); //开始播放 animationDrawable.start(); }else if (code==GifImage.STATUS_FORMAT_ERROR){ Toast.makeText(this, "该图片格式不是gif格式", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "gif图片读取失败"+code, Toast.LENGTH_SHORT).show(); } } }