使用Glide和android-gif-drawable加载普通图片和gif图片

2017-05-04 - 5,550 Views - 0 Goods - Nothing

Android本身的ImageView不支持播放gif,所以我借助github上的开源库来android-gif-drawable实现播放gif,图片加载缓存框架我用的是Glide

因为加载gif和普通图片用的是不同的方法,所以首先我实现了一个异步任务类来加载图片文件

/**
 * Created by xesygao on 2017/5/4 0004.
 * Email: [email protected]
 */

public class DlImageTask extends AsyncTask {
    private Context appContext;
    private int progress;
    private String url;
    private OnImageLoaded onImageLoaded;

    public DlImageTask(Context appContext, String url, OnImageLoaded onImageLoaded) {
        this.appContext = appContext;
        this.url=url;
        this.onImageLoaded=onImageLoaded;
    }

    @Override
    protected String doInBackground(Integer... integers) {
        GifDrawable gifDrawable=null;
        File file=null;
        InputStream is=null;
        try {
            //使用Glide获取图片文件
            file= Glide.with(appContext)
                    .load(url)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
            is=new BufferedInputStream(new FileInputStream(file));
            //输入流需要支持mark,在java.io包中,“仅有两个类始终支持标记(BufferedInputStream和ByteArrayInputStream)
            //假设图片为gif,如果不是,抛出GifIOException
            gifDrawable=new GifDrawable(is);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (GifIOException e){
            //捕获GifIOException,将该图片资源当成普通图片处理
            Bitmap bitmap= BitmapFactory.decodeFile(file.getPath());
            //回调函数
            onImageLoaded.onSuccess(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }
        if(gifDrawable!=null){
            onImageLoaded.onGifSuccess(gifDrawable);
        }
        return "success";
    }

}

注释写的很清楚了,我就不多费口舌了
图片加载成功后执行一个回调函数,接口如下,具体实现根据业务需求自己去实现

public interface OnImageLoaded {
    //gif图片回调这个
    public void onGifSuccess(GifDrawable gifDrawable);
    //普通图片回调这个
    public void onSuccess(Bitmap bitmap);
    //图片加载失败
    public void onFailed();
}
转载请注明原文链接:首页 -> 学习记录 -> Android学习记录 -> 使用Glide和android-gif-drawable加载普通图片和gif图片

FuZhou . FuJian

"Never start something you're not willing to finish"