天天看點

Android 顯示Gif動态圖和靜态圖

今天寫了個demo來顯示網絡圖檔,靜态圖都好說,很容易就可以顯示,但是動态圖呢?安卓裡是沒有自帶的控件來顯示gif圖的,開發大神們可以自己寫View來支援gif,我這邊是用了開源的控件,不多說了,上圖和代碼。

下載下傳位址:android-gif-drawable的源代碼下載下傳位址:https://github.com/koral–/android-gif-drawable

先上顯示的效果圖:靜态圖和動态圖

Android 顯示Gif動态圖和靜态圖
Android 顯示Gif動态圖和靜态圖

1、靜态圖代碼:

從網絡上根據圖檔位址來擷取圖檔:連接配接位址—>用流讀資料—>流轉換成bitmap

class HttpGetMap {

public static Bitmap getNetWorkBitmap(String urlString) {

URL imgUrl = null;

Bitmap bitmap = null;

InputStream is = null;

try {

imgUrl = new URL(urlString);

// 使用HttpURLConnection打開連接配接

HttpURLConnection urlConn = (HttpURLConnection) imgUrl

.openConnection();

urlConn.setDoInput(true);

urlConn.setRequestMethod(“GET”);

urlConn.connect();

//響應碼為200,則通路成功

if (urlConn.getResponseCode() == 200) {

// 将得到的資料轉化成InputStream

is = urlConn.getInputStream();

// 将InputStream轉換成Bitmap

bitmap = BitmapFactory.decodeStream(is);

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

if (is != null) {

is.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

return bitmap;

}

}

異步加載圖檔,直接調用上面的方法,然後setImageBitmap就好了

Android 顯示Gif動态圖和靜态圖

2、動态圖代碼:

當時做這個耗了點時間,一開始的思路和顯示靜态圖一樣,效果是動态圖能顯示,但是動态圖變靜态圖了;後來把流轉換成GifDrawable,但是圖檔顯示不了;這是最後改的,直接下載下傳那個圖檔,然後再顯示,就可以了

public void displayImage(String url, File saveFile, final GifImageView gifView){
        HttpUtils http = new HttpUtils();
        http.download(url, saveFile.getAbsolutePath(), new RequestCallBack<File>() {
            public void onSuccess(ResponseInfo<File> responseInfo) {
                try {
                    GifDrawable gifFrom = new GifDrawable( responseInfo.result.getAbsolutePath() );
                    gifView.setImageDrawable(gifFrom);
                }
                catch(Exception e){
                }
            }
            public void onFailure(HttpException error, String msg) {
            }
        });
    }

public File getFilesDir(Context context, String tag){
    if(isSdCardExist() == true){
        return context.getExternalFilesDir(tag);
    }
    else{
        return context.getFilesDir();
    }
}

public File getImageDir(Context context){
    File file = getFilesDir(context, "images");
    return file;
}

public boolean isSdCardExist() {
    if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        return true;
    }
    return false;
}
           

圖檔拿到了,下面是調用上面的方法顯示出來(imgUrl 是網絡圖檔的位址,mImg是GifImageView)

File saveImgPath = this.getImageDir(this);
        File gifSavePath = new File(saveImgPath, "gif");
        displayImage(imgUrl, gifSavePath, mImg);