天天看點

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動畫 GifView