Glide作为我们主要的图片加载工具,这里我写了一个封装类,方便我们的调用。
首先第一步,我们要引入Glide的依赖
//Glide图片加载框架
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
接着要引入我们的工具类
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
/**
* 图片加载库
* Created by WaterWood on 2018/6/5.
*/
public class ImageLoader {
private static ImageLoader imageLoader;
/**
* 获取对象实例
* @return
*/
public static ImageLoader getInstance() {
if (imageLoader == null) {
imageLoader = new ImageLoader();
}
return imageLoader;
}
/**
* 加载图片
* @param context 上下文
* @param imgUrl 图片地址
* @param defaultPic 占位图
* @param errorPic 错误加载图
*/
public void loadImage(Context context, String imgUrl, int defaultPic,int errorPic,ImageView imageView){
final RequestOptions options = new RequestOptions();
options.skipMemoryCache(false);
options.diskCacheStrategy(DiskCacheStrategy.ALL);
options.priority(Priority.HIGH);
options.error(errorPic);
options.placeholder(defaultPic);
Glide.with(context).load(imgUrl).apply(options).into(imageView);
}
/**
* 加载圆角图片
* @param context
* @param imgUrl
* @param round
* @param imageView
*/
public void loadCornerImage(Context context,String imgUrl,int round,ImageView imageView){
Glide.with(context)
.load(imgUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCorners(round)))//圆角半径
.into(imageView);
}
/**
* 加载圆形图片
* @param context
* @param imgUrl
* @param imageView
*/
public void loadRoundImage(Context context,String imgUrl,ImageView imageView){
Glide.with(context)
.load(imgUrl)
.apply(RequestOptions.bitmapTransform(new CircleCrop()))
.into(imageView);
}
/**
* 加载资源图片
* @param context 上下文
* @param imgResource 资源图片
* @param defaultPic 占位图
* @param errorPic 错误加载图
*/
public void loadImage(Context context, int imgResource, int defaultPic,int errorPic,ImageView imageView){
final RequestOptions options = new RequestOptions();
options.skipMemoryCache(false);
options.diskCacheStrategy(DiskCacheStrategy.ALL);
options.priority(Priority.HIGH);
options.error(errorPic);
options.placeholder(defaultPic);
Glide.with(context).load(imgResource).apply(options).into(imageView);
}
}
这里提供了资源图片,圆形,圆角和普通图片四种加载的方法,基本满足我们日常开发中的使用。