版本:Glide4.7.1
1.配置
1.1.新建一个MyAppGlideModule继承AppGlideModule,建议使用官方使用的方法,方便后续需求而进行拓展配置
@GlideModule
public class MyAppGlideModule extends AppGlideModule {
@Override
public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
//下面3中设置都可自定义大小,以及完全自定义实现
//内存缓冲
MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context)
.setMemoryCacheScreens(2)
.setBitmapPoolScreens(3)
.build();
builder.setMemoryCache(new LruResourceCache(calculator.getMemoryCacheSize()));
//Bitmap 池
builder.setBitmapPool(new LruBitmapPool(calculator.getBitmapPoolSize()));
//磁盘缓存
int diskCacheSizeBytes = 1024 * 1024 * 100; //100 MB
builder.setDiskCache(new InternalCacheDiskCacheFactory(context, diskCacheSizeBytes));
}
}
1.2.新建一个封装类GlideUtil,方便以后得维护。目前没有进行很好的封装,方便自己的需求添加,可以根据自己的需要进行修改
/**
* 创建日期:2018/11/23 on 10:38
* 描述: glide工具类
*/
public class GlideUtil {
private static GlideUtil instance;
RequestOptions options;
Context mContext;
private GlideUtil(Context context){
options = new RequestOptions();
options.skipMemoryCache(false);
options.diskCacheStrategy(DiskCacheStrategy.ALL);
options.priority(Priority.HIGH);
options.error(R.mipmap.home_img_loading_pic1);
//设置占位符,默认
options.placeholder(R.mipmap.home_img_loading_pic1);
//设置错误符,默认
options.error(R.mipmap.home_img_loading_pic1);
mContext=context;
}
public static GlideUtil getInstance(Context context){
if (instance==null){
synchronized (GlideUtil.class){
if (instance==null){
instance=new GlideUtil(context);
}
}
}
return instance;
}
//设置占位符
public void setPlaceholder(int id){
options.placeholder(id);
}
public void setPlaceholder(Drawable drawable){
options.placeholder(drawable);
}
//设置错误符
public void setError(int id){
options.error(id);
}
public void setError(Drawable drawable){
options.error(drawable);
}
public void showImage(String url, ImageView imageView){
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
//以图片宽度为基准
public void showImageWidthRatio(String url, final ImageView imageView, final int width){
GlideApp.with(mContext)
.asBitmap()
.apply(options)
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth=resource.getWidth();
int imageHeight=resource.getHeight();
int height = width * imageHeight / imageWidth;
ViewGroup.LayoutParams params=imageView.getLayoutParams();
params.height=height;
params.width=width;
imageView.setImageBitmap(resource);
}
});
}
//以图片高度为基准
public void showImageHeightRatio(String url, final ImageView imageView, final int height){
GlideApp.with(mContext)
.asBitmap()
.apply(options)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth=resource.getWidth();
int imageHeight=resource.getHeight();
int width = height * imageHeight / imageWidth;
ViewGroup.LayoutParams params=imageView.getLayoutParams();
params.height=height;
params.width=width;
imageView.setImageBitmap(resource);
}
});
}
//设置图片固定的大小尺寸
public void showImageWH(String url, final ImageView imageView, int height,int width){
options.override(width,height);
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
//设置图片圆角,以及弧度
public void showImageRound(String url, final ImageView imageView,int radius){
options.transform(new CornersTranform(radius));
// options.transform(new GlideCircleTransform());
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
public void showImageRound(String url, final ImageView imageView,int radius, int height,int width){
//不一定有效,当原始图片为长方形时设置无效
options.override(width,height);
options.transform(new CornersTranform(radius));
// options.centerCrop(); //不能与圆角共存
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
public void showImageRound(String url, final ImageView imageView){
//自带圆角方法,显示圆形
options.circleCrop();
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
}
1.3使用方式
GlideUtil.getInstance(context).showImageRound(aNew.getImages_urls().get(0),vh.img_news_pic1);
2.特殊需求,以及注意事项
2.1挡我们需要给图片使用圆角的时候我们需要进行一些处理。
有两种方式:
a.可以根据Glide提供扩展接口自己实现方法(4.0之前和之后的版本的实现方式有点不一样)
/**
* glide处理圆角图片\
*/
public class CornersTranform extends BitmapTransformation {
private float radius;
public CornersTranform() {
super();
radius = 10;
}
public CornersTranform(float radius) {
super();
this.radius = radius;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return cornersCrop(pool, toTransform);
}
private Bitmap cornersCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
if (result != null && !result.isRecycled()){
result.recycle();
result = null;
}
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
}
}
实现方法
public void showImageRound(String url, final ImageView imageView,int radius, int height,int width){
//不一定有效,当原始图片为长方形时设置无效
options.override(width,height);
options.transform(new CornersTranform(radius));
// options.centerCrop(); //不能与圆角共存
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
上面的方式可以自定义圆角弧度的,注意不能options.centerCrop();一起使用,因为一起使用会让圆角失效(原因网上已经有解释以及实现共存方式)
glide官方还提供了 options.circleCrop();方法这是实现圆形的图片
//自带圆角方法,显示圆形
options.circleCrop();
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
b.上面的方式个人感觉不是太友好,我采取的是自定义一个实现圆角的控件
RoundImageView实现圆角弧度,实现和使用简单,但不能随意修改
/**
* 创建日期:2018/10/19 on 15:38
* 描述: 自定义圆角图片
*/
public class RoundImageView extends AppCompatImageView {
//圆角大小,默认为10
private int mBorderRadius = 10;
private Paint mPaint;
// 3x3 矩阵,主要用于缩小放大
private Matrix mMatrix;
//渲染图像,使用图像为绘制图形着色
private BitmapShader mBitmapShader;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mMatrix = new Matrix();
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null){
return;
}
Bitmap bitmap = drawableToBitamp(getDrawable());
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
float scale = 1.0f;
if (!(bitmap.getWidth() == getWidth() && bitmap.getHeight() == getHeight()))
{
// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(),
getHeight() * 1.0f / bitmap.getHeight());
}
// shader的变换矩阵,我们这里主要用于放大或者缩小
mMatrix.setScale(scale, scale);
// 设置变换矩阵
mBitmapShader.setLocalMatrix(mMatrix);
// 设置shader
mPaint.setShader(mBitmapShader);
canvas.drawRoundRect(new RectF(0,0,getWidth(),getHeight()), mBorderRadius, mBorderRadius,
mPaint);
}
private Bitmap drawableToBitamp(Drawable drawable)
{
if (drawable instanceof BitmapDrawable)
{
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}
// 当设置不为图片,为颜色时,获取的drawable宽高会有问题,所有当为颜色时候获取控件的宽高
int w = drawable.getIntrinsicWidth() <= 0 ? getWidth() : drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight() <= 0 ? getHeight() : drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
}
//使用:在对应的布局文件中使用
<com.bestapp.myglidedemo.image.RoundImageView
android:id="@+id/img_news_pic1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/news_type_bottom"
android:scaleType="centerCrop"
android:src="@mipmap/home_img_loading_pic1" />
CustomRoundAngleImageView实现比较复杂,但是可以单独随意定义4个角的弧度
/**
* 创建日期:2018/10/22 on 11:24
*/
public class CustomRoundAngleImageView extends AppCompatImageView {
float width, height;
public CustomRoundAngleImageView(Context context) {
this(context, null);
init(context, null);
}
public CustomRoundAngleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init(context, attrs);
}
public CustomRoundAngleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private int defaultRadius = 0;
private int radius;
private int leftTopRadius;
private int rightTopRadius;
private int rightBottomRadius;
private int leftBottomRadius;
private void init(Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT < 18) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// 读取配置
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Custom_Round_Image_View);
radius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_radius, defaultRadius);
leftTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_top_radius, defaultRadius);
rightTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_top_radius, defaultRadius);
rightBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_bottom_radius, defaultRadius);
leftBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_bottom_radius, defaultRadius);
//如果四个角的值没有设置,那么就使用通用的radius的值。
if (defaultRadius == leftTopRadius) {
leftTopRadius = radius;
}
if (defaultRadius == rightTopRadius) {
rightTopRadius = radius;
}
if (defaultRadius == rightBottomRadius) {
rightBottomRadius = radius;
}
if (defaultRadius == leftBottomRadius) {
leftBottomRadius = radius;
}
array.recycle();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
@Override
protected void onDraw(Canvas canvas) {
//这里做下判断,只有图片的宽高大于设置的圆角距离的时候才进行裁剪
int maxLeft = Math.max(leftTopRadius, leftBottomRadius);
int maxRight = Math.max(rightTopRadius, rightBottomRadius);
int minWidth = maxLeft + maxRight;
int maxTop = Math.max(leftTopRadius, rightTopRadius);
int maxBottom = Math.max(leftBottomRadius, rightBottomRadius);
int minHeight = maxTop + maxBottom;
if (width >= minWidth && height > minHeight) {
Path path = new Path();
//四个角:右上,右下,左下,左上
path.moveTo(leftTopRadius, 0);
path.lineTo(width - rightTopRadius, 0);
path.quadTo(width, 0, width, rightTopRadius);
path.lineTo(width, height - rightBottomRadius);
path.quadTo(width, height, width - rightBottomRadius, height);
path.lineTo(leftBottomRadius, height);
path.quadTo(0, height, 0, height - leftBottomRadius);
path.lineTo(0, leftTopRadius);
path.quadTo(0, 0, leftTopRadius, 0);
canvas.clipPath(path);
}
super.onDraw(canvas);
}
}
新建一个资源文件attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Custom_Round_Image_View">
<attr name="radius" format="dimension"/>
<attr name="left_top_radius" format="dimension"/>
<attr name="right_top_radius" format="dimension"/>
<attr name="right_bottom_radius" format="dimension"/>
<attr name="left_bottom_radius" format="dimension"/>
</declare-styleable>
</resources>
使用
<com.bestapp.myglidedemo.image.CustomRoundAngleImageView
android:id="@+id/img_type3_pic1"
android:layout_width="200px"
android:layout_height="200px"
android:scaleType="centerCrop"
app:left_top_radius="10px"
app:left_bottom_radius="10px"
android:src="@mipmap/home_img_loading_pic1" />
注意:com.bestapp.myglidedemo.image.是自己文件所在的路径,根据自己的情况修改
2.2设置图片宽高
2.2.1 根据宽度为基准设置图片宽高
//以图片宽度为基准
public void showImageWidthRatio(String url, final ImageView imageView, final int width){
GlideApp.with(mContext)
.asBitmap()
.apply(options)
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth=resource.getWidth();
int imageHeight=resource.getHeight();
int height = width * imageHeight / imageWidth;
ViewGroup.LayoutParams params=imageView.getLayoutParams();
params.height=height;
params.width=width;
imageView.setImageBitmap(resource);
}
});
}
2.2.2根据高度为基准设置图片宽高
//以图片高度为基准
public void showImageHeightRatio(String url, final ImageView imageView, final int height){
GlideApp.with(mContext)
.asBitmap()
.apply(options)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth=resource.getWidth();
int imageHeight=resource.getHeight();
int width = height * imageHeight / imageWidth;
ViewGroup.LayoutParams params=imageView.getLayoutParams();
params.height=height;
params.width=width;
imageView.setImageBitmap(resource);
}
});
}
2.2.3单独设置宽高使用options.override(width,height);方法
总结:基本可以概括了一般的使用,当然还有更高级的使用还没有涉及到。本文是根据本人自己的项目情况遇到的问题来写的,当然同时借鉴了网上的东西,有什么不对的希望指出。
网友评论