一个简易的ImageLoader,集成图片缓存,图片下载,图片加载到ImageView

1.实际效果:

这里写图片描述

2.使用方法:

1.
ImageLoaderConfig config=new ImageLoaderConfig.Builder()
                        .setImageHeigth(0)   
                        .setImageWidth(0)     
                        .setLoadingImageResource(R.drawable.loading) 
                        .setLoadingFailedImageResource(R.drawable.failed) 
                        .setImageQuality(Bitmap.Config.RGB_565) 
                        .create();//链式调用,配置属性(create最后调用)
ImageLoader loader=ImageLoader.getInstance();//初始化ImageLoader
loader.setConfig(config);//为loader加载配置

2.
 App.getInstance().loader.displayImage(context,imageUrl,imagView);//调用图片加载方法

1,建议在系统启动时初始化,如在Application的子类App中初始化,通过Application子类的静态方法getInstance()获取其子类对象。
2,在需要的地方引用即可,如在BaseAdapter类getView方法中为ImageView设置图片时:

App.getInstance().loader.displayImage(context,bean.getUrl(),(ImageView) viewHolder.getView(R.id.myimage));

3.代码实现:

一,ImageLoader类

其中包含几个重要的类:ImageCache(图片缓存类),DownloadTask(图片下载类),ImageLoaderConfig(图片设置类),接下来会逐一描述,先来讲ImageLoader ,因为使用了Volley,所以就没用线程池了。

package capton.chen.imageloader;

import android.content.Context; 
import android.widget.ImageView; 

/**
 * Created by CAPTON on 2017/1/7.
 */

public class ImageLoader {

    private  ImageCache mImageCache=new ImageCache();//图片缓存类
    private ImageLoaderConfig mConfig; //图片设置类。设置图片的宽,高,质量;设置加载中,加载失败图片
    private static ImageLoader mInstance;//声明单例对象

    /*
    * 静态内部类方式实现单例对象的获取
    * */
    public static ImageLoader getInstance(){
        return ImageLoaderHoler.mInstance;
    }
    private static class ImageLoaderHoler{
        private static final  ImageLoader mInstance=new ImageLoader();//单例对象
    }

     /*
     * 获取设置图片设置类
     * */
    public void setConfig(ImageLoaderConfig mConfig){this.mConfig=mConfig;}

    /*
    * 加载图片
    * */
    public void displayImage(Context context, String imageUrl, ImageView imageView) {

        //根据图片url判断缓存中是否有下载好的图片。有,则从缓存中取出;无,则调用下载方法
        if (mImageCache.get(imageUrl) != null) {
            imageView.setImageBitmap(mImageCache.get(imageUrl));
        } else {
            imageView.setTag(imageUrl);//设置Tag防止输出图片错位加载;
            downLoadImage(context, imageUrl, imageView);
        }

    }
    /*
    * 下载方法
    * */
    private void downLoadImage( Context context,  String imageUrl,  ImageView imageView)  {
        DownloadTask downloadTask=new DownloadTask(context,imageUrl,imageView);//初始化下载类
        downloadTask.initSettings(mConfig,mImageCache);//为下载类添加图片设置类
        downloadTask.run();//开始下载任务
    }
}

二,ImageCache类

这个类挺简单的,用到了LruCache缓存。

package capton.chen.imageloader;


import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

/**
 * Created by CAPTON on 2017/1/7.
 */

public class ImageCache {

    private LruCache<String,Bitmap> imageCache;
    private  long maxMemory=Runtime.getRuntime().maxMemory()/1024;
    private  int cacheSize= (int) (maxMemory/8);//图片缓存设置为系统最大缓存的1/8; 

    public ImageCache( ) {
       imageCache=new LruCache<String,Bitmap>(cacheSize){
           @Override
           protected int sizeOf(String key, Bitmap value) {
               return value.getRowBytes()*value.getHeight()/1024;
           }
       };
    }
    /*
    * 图片下载后调用此方法将图片添加到缓存中
    * */
    public void put(String url,Bitmap bitmap){
        if(bitmap!=null) {
            imageCache.put(url, bitmap);
        }else {
            throw  new NullPointerException("bitmap is null,please check it first");
        }
    }
    /*
    * 获取缓存中图片
    * */
    public Bitmap get(String url){
        Bitmap bitmap=null;
        bitmap=imageCache.get(url);
        return bitmap;
    }
    /*
    * 清除缓存
    * */
    public void clearCache(){
        if(imageCache!=null) {
            imageCache.evictAll();

        }else {
           throw  new NullPointerException("imageCache is null,please init first");
        }
    }
    /*
    * 移除某一张图片
    * */
    public boolean remove(String url){
        imageCache.remove(url);
        return imageCache.get(url)==null;
    }

}

三,图片设置类:ImageLoaderConfig

主要是用到了Builder模式,实现对象的唯一性,后续的引用都是指向一个ImageLoaderConfig 对象

package capton.chen.imageloader;

import android.graphics.Bitmap;

/**
 * Created by CAPTON on 2017/1/7.
 */

/*
* 设置图片宽高,质量的类
* */
public  class ImageLoaderConfig {

    private static ImageLoaderConfig mConfig;
    private  int imageWidth;
    private  int imageHeigth;
    private  Bitmap.Config  config;
    private int loadingImageId;
    private int loadFailedImageId;

    public int getLoadingImageId() {return loadingImageId;}

    public int getLoadFailedImageId() {return loadFailedImageId;}

    public int getImageWidth() {
        return imageWidth;
    }

    public Bitmap.Config getConfig() {
        return config;
    }

    public int getImageHeigth() {
        return imageHeigth;
    }

    private ImageLoaderConfig() {
        //防止用户通过此方法新建对象,保证设置的唯一性
    }
    /*
    * Builder模式初始化mConfig,产生一个唯一对象供后续类引用。
    * */
    public static class Builder{

        private int imageWidth;
        private int imageHeigth;
        private  Bitmap.Config  config;
        private int loadingImageId;
        private int loadFailedImageId;

        /*
        * 设置图片显示宽度(px)
        * */
        public Builder setImageWidth(int imageWidth) {
            this.imageWidth = imageWidth;
            return this;
        }
        /*
        * 设置图片显示高度(px)
        * */
        public Builder setImageHeigth(int imageHeigth) {
            this.imageHeigth = imageHeigth;
            return this;
        }
         /*
         * 设置图片显示质量
         * */
        public Builder setImageQuality(Bitmap.Config config) {
            this.config = config;
            return this;
        }
        /*
        * 设置加载中图片
        * */
        public Builder setLoadingImageResource(int resId){
            loadingImageId=resId==0?R.mipmap.ic_launcher:resId;
            return this;
        }
        /*
        * 设置加载失败图片
        * */
        public Builder setLoadFailedImageResource(int resId){
            loadFailedImageId=resId==0?R.mipmap.ic_launcher:resId;
            return this;
        }
        /*
        * 为设置类各个属性赋值
        * */
        private void initConfig(){
            mConfig.imageHeigth=this.imageHeigth;
            mConfig.imageWidth=this.imageWidth;
            mConfig.config=this.config;
            //若是用户没有调用setLoadingImageResource方法则用默认图片代替,可自行配置默认图片
            mConfig.loadingImageId=loadingImageId==0?R.mipmap.ic_launcher:loadingImageId;
            //若是用户没有调用setLoadFailedImageResource方法则用默认图片代替,可自行配置默认图片
            mConfig.loadFailedImageId=loadFailedImageId==0?R.mipmap.ic_launcher:loadFailedImageId;
        }
        /*
        * 生成唯一的ImageLoaderConfig对象,供后续类的引用。
        * */
        public  ImageLoaderConfig create(){
            mConfig=new ImageLoaderConfig();
            initConfig();
            return mConfig;
        }

    }

}

四 , 下载类:DownloadTask

负责图片的网络下载,图片加载到缓存,图片加载到Imageview

package capton.chen.imageloader;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;

/**
 * Created by CAPTON on 2017/1/8.
 */

/*
* 下载类
* */
public class DownloadTask{
    private String imageUrl;//图片地址
    private ImageView imageView;//需要加载图片的ImageView
    private  Context context;//异步加载需要使用的context对象
    private int width;//图片宽(px),若是超过实际像素,则按实际像素显示
    private int heigth;//图片高(px),若是超过实际像素,则按实际像素显示
    private ImageLoaderConfig mConfig;//图片设置类
    private ImageCache mImageCache;// 缓存类

    //get方法,按需求自行配置
    public ImageView getImageView() {return imageView;}
    public String getImageUrl() {
        return imageUrl;
    }

    /*
    * 构造方法
    * */
    public DownloadTask(Context context, String imageUrl, ImageView imageView) {
        this.imageUrl = imageUrl;
        this.imageView = imageView;
        this.context=context;
    }

    /*
    * 初始化设置类,缓存类
    * */
    public void initSettings(ImageLoaderConfig mConfig,ImageCache mImageCache){
        this.mConfig=mConfig;
        this.width=mConfig.getImageWidth();
        this.heigth=mConfig.getImageHeigth();
        this.mImageCache = mImageCache;
    }

    /*
    * 开始下载图片,使用Volley框架
    * Android Studio 下  compile 'com.mcxiaoke.volley:library:1.0.19'
    * */
    public void run() {
        RequestQueue queue= Volley.newRequestQueue(context);
        imageView.setImageResource(mConfig.getLoadingImageId());//设置加载中的图片
        ImageRequest request=new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                /*
                * 判断图片地址与imageView中的Tag是否一致,若是,才加载图片
                * */
                if(((String)imageView.getTag()).equals(imageUrl)) {
                    imageView.setImageBitmap(response);
                    mImageCache.put(imageUrl, response);//添加Bimap到缓存
                }
            }
        },width,heigth,mConfig.getConfig(),new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
             imageView.setImageResource(mConfig.getLoadFailedImageId());//设置下载失败时的提示图片
            }
        });
        queue.add(request);
    }
}

临时做的一个网络图片加载器,没有很多功能,缓存机制也太单一只有内存为载体,后续会试试补充本地缓存。

4.下载链接

关键文件:链接:http://pan.baidu.com/s/1i4B59sT 密码:o8a5
完整Android Studio项目: 链接:http://pan.baidu.com/s/1nv79SZB 密码:f9ev

猜你喜欢

转载自blog.csdn.net/ccapton/article/details/54236536
今日推荐