Android前端—显示GIF动画

Android前端—显示GIF动画

一、技术概述

  在Android原有组件的情况下,是不能打开GIF的动画的,GIF动画在ImageView中以静态的形式显示。
  我们希望在开发的过程中能够采用类似ImageView的工具打开GIF动画方便直接,同时可以实现与ImageView类似的功能。
  有以下几种方法:(1)Glide; (2)GifImageView; (3)GifView;

二、技术详述

1、Glide加载ImageView

//Java代码:
    public void loadimage(View view){
        String url="http://p1.pstatp.com/large/166200019850062839d3";
        int res= R.drawable.image;
        Glide.with(this).
            load(url).placeholder(res).
            error(R.drawable.eeror).
            diskCacheStrategy(DiskCacheStrategy.NONE).
            into(imageview);
    }

//build.gradle代码
    dependencies {     
    compile ´com.github.bumptech.glide:glide:3.7.0´ //加载glide

    compile fileTree(dir: ´libs´, include: [´*.jar´])
    androidTestCompile(´com.android.support.test.espresso:espresso-core:2.2.2´, {
        exclude group: ´com.android.support´, module: ´support-annotations´
    })
    compile ´com.android.support:appcompat-v7:25.0.1´
    testCompile ´junit:junit:4.12´
}

2、GifImageView

android-gif-drawable

//build.gradle代码dependencies中添加
    implementation ´pl.droidsonroids.gif:android-gif-drawable:1.2.16´

即可使用组件GifImageView

//activity_main.xml中
    <GifImageView 
        android:id="@+id/agif"
        android:onClick="onClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/gif3" />

3、GifView.jar项目

把GifView.jar加入你的项目

//activity_main.xml中配置GifView的基本属性
    <com.ant.liao.GifView android:id="@+id/gif2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:paddingTop="4px"
        android:paddingLeft="14px"
        android:enabled="false" />
//在Java代码中配置常用属性:
    //从xml中得到GifView的句柄
    gf1 = (GifView) findViewById(R.id.gif1);
    //设置Gif图片源
    gf1.setGifImage(R.drawable.gif1);
    //添加监听器
    gf1.setOnClickListener(this);
    //设置显示的大小,拉伸或者压缩
    gf1.setShowDimension(300, 300);
    //设置加载方式:先加载后显示:GifImageType.WAIT_FINISH、边加载边显示:GifImageType.SYNC_DECODER、只显示第一帧再显示:GifImageType.COVER
    gf1.setGifImageType(GifImageType.COVER);

三、技术使用中遇到的问题

  开发中我主要使用的是GifView,这个与其他控件不同的是一些属性(例如图片源、显示大小等)要在Java代码中设置。这个在一开始没有找到正确教程时造成了一定麻烦,自以为在xml文件中设置好了属性,运行之后却连图片都不显示。
  补充一个控制播放速度的技巧:eg.修改DrawThread中的SystemClock.sleep(10);

四、总结

  三种方式按需选择,总的来说是功能趋向丰富,但使用起来也更麻烦。能在前端布局中使用GIF动画能解决很多问题,还是很推荐的。

五、参考链接

android-gif-drawable
Android显示GIF动画 GifView

posted @ 2020-06-25 19:06  某糕  阅读(832)  评论(0编辑  收藏  举报