美文网首页安卓开发博客程序员Android开发经验谈
简单图片加载框架的打造-(了解如何设计一个图片加载框架)

简单图片加载框架的打造-(了解如何设计一个图片加载框架)

作者: Anderson大码渣 | 来源:发表于2017-08-22 17:36 被阅读473次

    目前市场上有很多第三方图片加载框架, 当然,以UniversalImageLoader,Picasso,Glide为代表, 这些图片加载库大大方便了我们平时使用时需要图片加载地方的代码编写,且其性能还高.

    之前学习了Volley的源码,生产者消费者模式的代码也看了很多,就想着试着自己打造一款图片加载框架,当然,功能与上面的比起来肯定有很多不足,不过锻炼一下框架思维也是不错的.

    先贴工程路径,里面还有我准备写的数据库lib,还有httplib,只看ImageLoaderlib即可.
    https://github.com/Jerey-Jobs/Sherlock

    简单图片加载框架需求

    1. 图片请求无需用户管理,分发器主动下载并设置图片
    2. 图片自适应ImageView大小,不能全部加载到内存
    3. TAG匹配,防止错位
    4. 灵活配置,加载时显示默认图片
    5. 自定义回调Callback,可让用户自己处理图片
    6. 图片加载策略选择,是后进优先加载还是先进优先加载
    7. 图片缓存策略配置,是否Disk缓存
    8. 能够主动取消请求.

    暂时先定这么多需求,至于像Glide那样绑定住Activity或者Fragment的生命周期的功能,我们知道它是通过注册一个空的Fragment来干的,但是先不做了.上面需求已经够我们做的了.

    我们可以想看一下我们设计的最终结果,其实还蛮让人期待的.

    SherlockImageLoader.with(this)
            .setUrl("http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg")
            .loadingImage(R.mipmap.ic_launcher_round)
            .errorImage(R.drawable.blog)
            .into(mImageView);
    
    SherlockImageLoader.with(this)
            .setUrl("http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg")
            .loadingImage(R.mipmap.ic_launcher_round)
            .errorImage(R.drawable.blog)
            .into(new SherlockImageLoader.Callback() {
                @Override
                public void onSuccess(Bitmap bitmap, String url) {
                    Log.i(TAG, "onSuccess: " + bitmap + " url" + url);
                }
            });
    

    框架设计

    我将该图片框架命名为:SherlockImageLoader, 其架构很简单,一个入口,学习Volley的方式,那就是是分发器,加载器,缓存容器外加一个配置选项就行了.

    框架如图:

    sherlockimageloader

    类的设计

    根据上面的框架,我们需要新建SherlockImageLoader类作为主入口,提供displayImage()方法,然后呢,RequestQueue类提供添加请求的队列,RequestDispacher负责从队列取请求进行分发,分发即是调用Loader去加载请求, 加载请求是根据Config加载的. Loader同时还依赖缓存容器,因为每次去加载时,都需要看缓存是否已经有了.

    跟着上面描述很简单.我们先开始写接口吧.

    SherlockImageLoader我们先将其设置为单列,之后可以再改,入口的封装留到最后.

    首先SherlockImageLoader需要持有一个队列和Config.还要提供显示方法给外部使用.代码如下.

    
    public class SherlockImageLoader {
    
        private ImageLoaderConfig mImageLoaderConfig;
        private RequestQueue mRequestQueue;
    
        /**
         * 单列对象
         */
        private static volatile SherlockImageLoader instance;
    
        public SherlockImageLoader(Context context, ImageLoaderConfig imageLoaderConfig) {
            if (imageLoaderConfig != null) {
                mImageLoaderConfig = imageLoaderConfig;
            } else {
                mImageLoaderConfig = new ImageLoaderConfig.Builder()
                        .setBitmapCache(new DoubleCache(context))
                        .setLoadPolicy(new ReverseLoaderPolicy())
                        .build();
            }
            mRequestQueue = new RequestQueue(mImageLoaderConfig.getTHREAD_COUNT());
            mRequestQueue.start();
        }
    
        public ImageLoaderConfig getImageLoaderConfig() {
            return mImageLoaderConfig;
        }
    
        public RequestQueue getRequestQueue() {
            return mRequestQueue;
        }
    
        /**
         * 初始化
         * @param context
         */
        public static void init(Context context) {
            init(context, null);
        }
    
        public static void init(Context context, ImageLoaderConfig config) {
            if (instance == null) {
                instance = new SherlockImageLoader(context, config);
            }
        }
    
        public static SherlockImageLoader getInstance() {
            if (instance == null) {
                throw new RuntimeException("SherlockImageLoader must init");
            }
    
            return instance;
        }
    
        public void display(ImageView imageView, String url) {
            display(imageView, url, null, null);
        }
    
    
        public void display(String url, Callback callback) {
            display(null, url, callback, null);
        }
    
        /**
         * @param imageView
         * @param url
         * @param callback
         */
        public void display(ImageView imageView, String url, Callback callback, DisplayConfig
                displayConfig) {
            BitmapRequest bitmapRequest = new BitmapRequest(imageView, url, callback, displayConfig);
            mRequestQueue.addRequest(bitmapRequest);
        }
    
    
        /**
         * 供用户自定义使用
         */
        public static interface Callback {
            /**
             * @param bitmap
             * @param url
             */
            void onSuccess(Bitmap bitmap, String url);
    
        }
    }
    
    

    缓存器与分发器是具体业务类,下章节设计,先写一下Loader,Cache,Config的接口,

    // Loader
    public interface ILoader {
        void loadImage(BitmapRequest request);
    }
    
    
    /**
     * 加载策略
     * @author xiamin
     * @date 7/8/17.
     */
    public interface ILoadPolicy {
    
        /**
         * 两个加载请求进行优先级比较
         * @param request1
         * @param request2
         * @return
         */
        int compareTo(BitmapRequest request1, BitmapRequest request2);
    }
    
    public interface BitmapCache {
    
        /**
         * 缓存bitmap
         * @param bitmapRequest
         * @param bitmap
         */
        void put(BitmapRequest bitmapRequest, Bitmap bitmap);
    
        /**
         * 通过请求取bitmap
         * @return
         */
        Bitmap get(BitmapRequest request);
    
        /**
         * 移除bitmap
         * @param request
         */
        void remove(BitmapRequest request);
    }
    

    思路很明朗到现在, 加载器就一个方法,加载请求, 策略呢也就是请求间的比较,谁大谁加载, 缓存呢就是存与取还有删除功能.

    请求封装

    我们的请求就是一个Bean类,里面的变量需要:

    /** 图片软应用,内存不足情况下不加载 */
    private SoftReference<ImageView> mImageViewSoftReference;
    /** 图片路径 */
    private String imageURL;
    /** 图片的md5码,做缓存唯一标识,因为图片名可能是非法字符,合法化一下 */
    private String imageUriMD5;
    /** 编号,请求的唯一标识 */
    private int serialNo;
    /** 下载完监听 */
    private SherlockImageLoader.Callback mCallback;
    /** 显示设置,要是为空,则使用全局的 */
    private DisplayConfig mDisplayConfig;
    /** 请求tag,供取消请求时使用 */
    private Object requestTag;
    /** 是否被取消 */
    private boolean isCancel = false;
    

    并设置相应的get和set方法.

    分发器设计RequestQueue]

    与Volley的代码一样,RequestQueue就是参考Volley设计的.

    RequestQueue的方法

    RequestQueue代码设计

    RequestQueue作为分发的源头,其一定持有一个Queue,然后持有Dispatchers来处理队列里面的请求.

    既然需要队列,我们这种生产者消费者模式对队列的要求是:

    • 线程安全
    • 能够阻塞
    • 能够优先级控制

    这样我们的数据结构只能是: PriorityBlockingQueue

    我们还需要分发器,从PriorityBlockingQueue中不断的take(), 然后进行处理, 因此我们需要一个分发器列表.这里参考Volley源码,使用一个数组来存储,毕竟数组够完成任务了.

    private RequestDispacher[] mRequestDispachers;
    

    我们还需要提供方法去让主程序start自己.stop自己.

    因此有了UML里面的start方法,stop方法.在这两个方法里面我们就开启分发器,关闭分发器就行了.

    分发器RequestDispacher设计

    分发器从PriorityBlockingQueue中取请求, 我大Java可没有那种什么全局变量的玩意儿,把PriorityBlockingQueue的引用传给RequestDispacher就行了,然后里面开一个线程不断的跑,从队列里取东西,进行消费就行了.

    那么我们的RequestDispacher就可以写成继承于Thread类, 正好也有start/stop方法可以供调用.

    代码编写

    在往RequesQueue添加请求的时候,我们可以直接给ImageView设置加载中的图片,虽然这个请求还未被处理,也就是还未被加载中,但是宏观来说,进入了我们的ImageLoader就已经是加载中了.

    public class RequestQueue {
    
        BlockingQueue<BitmapRequest> mRequestQueue = new PriorityBlockingQueue<>();
    
        private AtomicInteger mNo = new AtomicInteger(0);
    
        private int mThreadCount;
    
        private RequestDispacher[] mRequestDispachers;
    
        public RequestQueue(int threadCount) {
            mThreadCount = threadCount;
    
        }
    
        /**
         * start各个分发器
         */
        public void start() {
            mRequestDispachers = new RequestDispacher[mThreadCount];
            for (int i = 0; i < mRequestDispachers.length; i++) {
                RequestDispacher dispacher = new RequestDispacher(mRequestQueue);
                mRequestDispachers[i] = dispacher;
                dispacher.start();
            }
        }
    
        /**
         * 停止所有请求,以interrupt异常的方式
         * 分发器也会停止运行
         */
        public void stop() {
            for (int i = 0; i < mRequestDispachers.length; i++) {
                if (mRequestDispachers[i] != null) {
                    mRequestDispachers[i].quit();
                }
            }
        }
    
    
        /**
         * 取消所有请求,但不停止分发器的运行
         */
        public void cancel() {
            for (BitmapRequest request : mRequestQueue) {
                request.setCancel(true);
            }
        }
    
        /**
         * 根据tag取消请求
         * @param tag
         */
        public void cancel(Object tag) {
            if (tag == null) {
                return;
            }
    
            for (BitmapRequest request : mRequestQueue) {
                if (tag.equals(request.getRequestTag())) {
                    request.setCancel(true);
                }
            }
        }
    
        public void addRequest(BitmapRequest request) {
            if (!mRequestQueue.contains(request)) {
                /** 设置唯一标识 */
                request.setSerialNo(mNo.incrementAndGet());
                mRequestQueue.add(request);
                L.w("请求添加成功, 编号为:" + request.getSerialNo());
            } else {
                L.w("请求已经存在, 编号为:" + request.getSerialNo());
            }
            if (request.getDisplayConfig() != null
                    && request.getDisplayConfig().loadingImage != -1) {
                ImageView imageView = request.getImageView();
                if (imageView != null && imageView.getTag().equals(request.getImageURL())) {
                    imageView.setImageResource(request.getDisplayConfig().loadingImage);
                }
            }
        }
    }
    

    分发器的代码

    
    /**
     * 请求转发线程
     * 依赖于BitmapRequest
     * 依赖于Loader
     * Created by xiamin on 7/8/17.
     */
    public class RequestDispacher extends Thread {
    
        private BlockingQueue<BitmapRequest> mBitmapRequests;
    
        /** Used for telling us to die. */
        private volatile boolean mQuit = false;
    
    
        public RequestDispacher(BlockingQueue<BitmapRequest> requests) {
            mBitmapRequests = requests;
        }
    
        /**
         * Forces this dispatcher to quit immediately.  If any requests are still in
         * the queue, they are not guaranteed to be processed.
         */
        public void quit() {
            mQuit = true;
            interrupt();
        }
    
        @Override
        public void run() {
            /**不断获取请求,处理请求*/
            while (!isInterrupted()) {
                try {
                    BitmapRequest bitmapRequest = mBitmapRequests.take();
    
                    if (bitmapRequest.isCancel()) {
                        continue;
                    }
                    L.d("开始处理" + bitmapRequest.getSerialNo() + "号请求,线程号:" + Thread.currentThread()
                            .getId());
                    /**
                     * 处理请求对象
                     */
                    String type = parseURL(bitmapRequest.getImageURL());
                    ILoader l = LoaderManager.getInstance().getLoaderByType(type);
                    l.loadImage(bitmapRequest);
    
                } catch (InterruptedException e) {
                    // We may have been interrupted because it was time to quit.
                    e.printStackTrace();
                    if (mQuit) {
                        return;
                    }
                    continue;
                }
            }
        }
    
        /**
         * 解析图片来源
         * @param imageURL
         * @return
         */
        private String parseURL(String imageURL) {
            if (imageURL.contains("://")) {
                return imageURL.split("://")[0];
            }
    
            L.e("不支持的URL:" + imageURL);
            return " ";
    
        }
    }
    
    

    加载器缓存器的设计

    加载器与缓存器的接口都在一开始定好了,这边只需要完成其接口.我们看一下UML图

    Loader

    Loader我们实现一个实现ILoader的BaseLoader类,这边用到了策略模式,其下有加载本地图片的Loader,加载网络请求的Loader.

    BaseLoader类中,需要先去缓存中获取Bitmap,获取到了直接设置,获取不到,就去调用子类的加载方法去加载.

    public abstract class BaseLoader implements ILoader {
    
        public static BitmapCache mBitmapCache = SherlockImageLoader.getInstance()
                .getImageLoaderConfig()
                .getmBitmapCache();
        public static Handler handler = new Handler(Looper.getMainLooper());
    
        @Override
        public void loadImage(BitmapRequest request) {
            /** 从缓存中取bitmap */
            Bitmap bitmap = mBitmapCache.get(request);
    
            if (bitmap == null) {
                L.i("获取缓存失败,先显示Loading图");
                showLoadingImage(request);
    
                bitmap = onLoad(request);
    
                cacheBitmap(request, bitmap);
            }
    
            deliveryToUIThread(request, bitmap);
        }
    
        /**
         * 缓存图片
         * @param request
         * @param bitmap
         */
        private void cacheBitmap(BitmapRequest request, Bitmap bitmap) {
            if (request != null && bitmap != null) {
                synchronized (BaseLoader.class) {
                    mBitmapCache.put(request, bitmap);
                }
            }
        }
    
        protected abstract Bitmap onLoad(BitmapRequest request);
    
        /**
         * 显示加载中图片
         * @param request
         */
        private void showLoadingImage(final BitmapRequest request) {
            if (request.getDisplayConfig() != null) {
                final ImageView imageview = request.getImageView();
                if (imageview == null) {
                    return;
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        imageview.setImageResource(request.getDisplayConfig().loadingImage);
                    }
                });
            }
        }
    
    
        /**
         * 交给主线程显示
         * @param request
         * @param bitmap
         */
        protected void deliveryToUIThread(final BitmapRequest request, final Bitmap bitmap) {
            ImageView imageView = request.getImageView();
            L.d("deliveryToUIThread imageView = " + imageView);
            if (imageView == null) {
                return;
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    updateImageView(request, bitmap);
                }
            });
    
        }
    
        private void updateImageView(final BitmapRequest request, final Bitmap bitmap) {
            ImageView imageView = request.getImageView();
            L.d("更新UI");
            if (imageView == null) {
                L.d("为空.返回");
                return;
            }
    
            //加载正常  防止图片错位
            if (bitmap != null && imageView.getTag().equals(request.getImageURL())) {
                L.d("加载正常");
                imageView.setImageBitmap(bitmap);
            } else {
                L.d("加载失败,TAG不对");
            }
            //有可能加载失败
            if (bitmap == null
                    && request.getDisplayConfig() != null
                    && request.getDisplayConfig().failedImage != -1) {
                L.d("加载失败,显示默认");
                imageView.setImageResource(request.getDisplayConfig().failedImage);
            }
            //监听
            //回调 给圆角图片  特殊图片进行扩展
            if (request.getCallback() != null) {
                request.getCallback().onSuccess(bitmap, request.getImageURL());
            }
        }
    }
    
    

    缓存策略

    缓存直接写了几个实现BitmapCache接口的类就行了.

    • RAMCache内存缓存
      使用 LruCache<String, Bitmap> mLruCache;
    • RomCache磁盘缓存
      使用 DiskLruCache
    • DoubleCache
      即先从内存取,取不到从磁盘取.

    举个列子RAM缓存代码

    public class RAMCache implements BitmapCache {
    
        private LruCache<String, Bitmap> mLruCache;
    
        public RAMCache() {
            int maxSize = (int) (Runtime.getRuntime().maxMemory() / 4);
            L.d("RAMCache maxSize: " + maxSize);
            mLruCache = new LruCache<String, Bitmap>(maxSize) {
                @Override
                protected int sizeOf(String key, Bitmap value) {
                    int size = value.getRowBytes() * value.getHeight();
                    L.d("size = " + size);
                    return size;
                }
            };
        }
    
        @Override
        public void put(BitmapRequest bitmapRequest, Bitmap bitmap) {
            mLruCache.put(bitmapRequest.getImageUriMD5(), bitmap);
        }
    
        @Override
        public Bitmap get(BitmapRequest request) {
            return mLruCache.get(request.getImageUriMD5());
        }
    
        @Override
        public void remove(BitmapRequest request) {
            mLruCache.remove(request.getImageUriMD5());
        }
    }
    
    

    封装

    几个关键的类都设计完了,该我们封装打通的时候呢,我一直喜欢RESTful风格,况且现在是2017年代码调用还不链式不能忍.

    看一下我们最终希望调用的方式.

    SherlockImageLoader.with(this)
            .setUrl("http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg")
            .loadingImage(R.mipmap.ic_launcher_round)
            .errorImage(R.drawable.blog)
            .into(mImageView);
    
    SherlockImageLoader.with(this)
            .setUrl("http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg")
            .loadingImage(R.mipmap.ic_launcher_round)
            .errorImage(R.drawable.blog)
            .into(new SherlockImageLoader.Callback() {
                @Override
                public void onSuccess(Bitmap bitmap, String url) {
                    Log.i(TAG, "onSuccess: " + bitmap + " url" + url);
                }
            });
    

    这是一个当前流行的调用风格,我们这个是简单的图片加载框架,没有Glide的功能那么多,只提供了上面显示的这些接口.

    with的不是绑定生命周期,而是用来tag,即强制将每次申请都绑定tag,这样我们可以在onDestroy的时候可以取消请求.

    ps: Glide的with是使用的注册一个空的Fragment来绑定调用方的生命周期,从而做到不需要请求方主动去取消请求的功能,我们这个框架那样写就复杂多了.with的对象有好多种的.

    好了,开始封装

    Builder的编写

    with(Obj tag)方法肯定是SherlockImageLoader的一个静态方法, 返回一个Builder就行了.

    public static RequestBuilder with(Object tag) {
        return new RequestBuilder(tag);
    }
    

    这个Builder里面有into方法, 相当于exec or build,

    代码如下:

    /**
     * @author xiamin
     * @date 7/18/17.
     */
    public class RequestBuilder {
    
        private String url;
        /** 显示设置,要是为空,则使用全局的 */
        private DisplayConfig mDisplayConfig;
        /** 请求tag,供取消请求时使用 */
        private Object requestTag;
    
    
        public RequestBuilder(Object requestTag) {
            this.requestTag = requestTag;
        }
    
        public RequestBuilder withDisplayConfig(DisplayConfig displayConfig) {
            mDisplayConfig = displayConfig;
            return this;
        }
    
        public RequestBuilder loadingImage(int loadingImage) {
            if (mDisplayConfig == null) {
                mDisplayConfig = new DisplayConfig();
            }
            mDisplayConfig.loadingImage = loadingImage;
            return this;
        }
    
        public RequestBuilder errorImage(int errorImage) {
            if (mDisplayConfig == null) {
                mDisplayConfig = new DisplayConfig();
            }
            mDisplayConfig.failedImage = errorImage;
            return this;
        }
    
    
        public RequestBuilder setUrl(String url) {
            this.url = url;
            return this;
        }
    
        public void into(ImageView imageView) {
            if (imageView == null) {
                throw new IllegalArgumentException("imageview can not be null");
            }
    
            BitmapRequest bitmapRequest = new BitmapRequest(imageView, url, null, mDisplayConfig);
            bitmapRequest.setRequestTag(requestTag);
            SherlockImageLoader.getInstance().display(bitmapRequest);
        }
    
        public void into(SherlockImageLoader.Callback callback) {
            if (callback == null) {
                throw new IllegalArgumentException("callback can not be null");
            }
    
            BitmapRequest bitmapRequest = new BitmapRequest(null, url, callback, mDisplayConfig);
            bitmapRequest.setRequestTag(requestTag);
            SherlockImageLoader.getInstance().display(bitmapRequest);
        }
    
    }
    
    

    很简单, 我们提供了上述接口, 然后在在调用方就能像上面那样调用了.

    完善

    • 对于Cancel请求, 一个请求可能在走到任何地方的时候被Cancel掉,因此其实我们应该尽可能的在多处关键点进行请求是否已经被Cancel的判断.被Cancel就结束.

    • 对于生命周期的绑定,上面说过了,需要向调用方注册一个空Fragment来进行监听生命周期,此功能暂时未做.

    • 对于错误回调,因为是图片加载,错误我们都'catch'了,没有传递到回调里面

    • 各类型的支持,我们这边只进行了Bitmap的编写,各种Drawable均未支持,这种级别的支持工程量就大了

    总结

    这个图片框架只是一个简单的图片框架,不过是为了锻炼框架思维所编写,真实情况下我们还是用Picasso,Glide比较好,毕竟JakeWharton的确强啊。

    工程路径:

    里面还有我准备写的数据库lib,还有httplib,只看ImageLoaderlib即可.
    https://github.com/Jerey-Jobs/Sherlock


    本文作者:Anderson/Jerey_Jobs

    博客地址 : http://jerey.cn/
    简书地址 : Anderson大码渣
    github地址 : https://github.com/Jerey-Jobs

    相关文章

      网友评论

        本文标题:简单图片加载框架的打造-(了解如何设计一个图片加载框架)

        本文链接:https://www.haomeiwen.com/subject/xhildxtx.html