Universal-Image-Loader加载Gif

昨日在某干货群里,有人问项目中已有ImageLoader怎么去加载Gif图片。多数人的回答都是使用Glide去替换ImageLoader。

Glide加载网络Gif的速度,想必尝试过的童鞋,应该都不敢恭维了,那是龟速啊…😂

自己也反编译过百思不得姐等App,发现android-gif-drawable使用率最高的库,可以偷偷告诉你们在AS里面使用这个库也是相当的方便。

  • ImageLoader加载Gif的时候只能显示Gif的某一帧,但实际上完整的Gif文件已经在缓存中。

  • android-gif-drawable这货只支持加载本地的文件。

这两个先天的特性,成就了这对好基友👫。

话说到这份上了,前方就是本文的最高能代码了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private static void displayImage(final ImageView pImageView, final String pUrl, final DisplayImageOptions pOptions,
final boolean retryWithClearMemoryCache)
{

ImageLoader.getInstance().displayImage(pUrl, pImageView, pOptions, new ImageLoadingListener() {

@Override
public void onLoadingComplete(String s, View pView, Bitmap pBitmap) {
final File inCache = DiskCacheUtils.findInCache(s, ImageLoader.getInstance().getDiskCache());
if (inCache == null || !inCache.exists()) {
if (retryWithClearMemoryCache) {
// 清理一遍内存区域
MemoryCacheUtils.removeFromCache(pUrl, ImageLoader.getInstance().getMemoryCache());
displayImage(pImageView, pUrl, pOptions, false);
}
return;
}

if (Utils.isGifFile(inCache.getAbsolutePath())) {
try {
GifDrawable gifDrawable = new GifDrawableBuilder().from(inCache).build();
pImageView.setImageDrawable(gifDrawable);
} catch (IOException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {

}
}
}
});
}

有没有很简洁,很有爱。一个负责下载,一个负责加载,成为了彼此的天使。

送佛送到西,再送一个Gif格式判断的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

public static boolean isGifFile(String path) {
final int HEAD_COUNT = 3;
if (TextUtils.isEmpty(path)) {
return false;
}
boolean isGif = false;
InputStream stream = null;
try {
stream = new FileInputStream(path);
byte[] head = new byte[HEAD_COUNT];
stream.read(head);
String imgType = new String(head);
isGif = imgType.equalsIgnoreCase("gif");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isGif;
}

华丽分割线之后,聊聊ImageLoader其他常被问到的问题

  • Question:ImageLoader 能加载圆角/圆形 图片吗?

    Answer:嗯嗯,是的 这货可以。

    1
    2
    3
    DisplayImageOptions options = new DisplayImageOptions.Builder()
    .displayer(new RoundedBitmapDisplayer(10))// 加载圆角图片
    .build();
  • Question: 相同的Uri,图片已经替换,怎么加载不出来?

    Answer: ImageLoader智能的过滤了已经在缓存中的Uri,不去加载。

    1
    2
    NonViewAware aware = new NonViewAware(size, ViewScaleType.CROP);
    ImageLoader.getInstance().displayImage(uri, aware, listener);

    对同一个URI进行多次请求,listener监听事件也不会被过滤,每一个请求都会获得相应的回应。

  • Question: ImageLoader 能加载本地图片吗?

    Answer:只需在我们的常用SD-CARD文件路径前加上

    1
    "file://"

    作为displayImage方法中的uri参数。

瞎逼逼到这里已经 扯不下去了,有误之处还望指出。

最后我本着一分$也是爱的态度,实验性地附上本人的重要社交方式(憋说话,输密码就好😂)。

支付宝 二维码
微信 二维码