有时候头像需求带圆角或者是圆形头像,而Glide本身并不具备自己加载圆形图片的功能,所以需要重写BitmapTransformation来达到需求
//加载圆形图片
public class GlideGetCircle extends BitmapTransformation {
public GlideGetCircle(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override public String getId() {
return getClass().getName();
}
}
//加载带圆角的图片
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
public GlideRoundTransform(Context context) {
this(context, 4);
}
public GlideRoundTransform(Context context, int dp) {
super(context);
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return roundCrop(pool, toTransform);
}
private static Bitmap roundCrop(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 = 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 String getId() {
return getClass().getName() + Math.round(radius);
}
}
//在MainActivity中加载圆形图片,主要代码如下:
private ImageView imageView;
private RequestManager glideRequest;
imageView = (ImageView) findViewById(R.id.imageView);
glideRequest = Glide.with(this);
//加载普通图片
glideRequest.load("图片url").into(imageView);
//加载圆角图片
glideRequest.load("图片url").transform(new GlideRoundTransform(context)).into(imageView);
//指定圆角半径
glideRequest.load("图片url").transform(new GlideRoundTransform(context, 10)).into(imageView);
//加载圆形图片
glideRequest.load("图片url").transform(new GlideGetCircle(context)).into(imageView);
好啦,这样就可以干净利落的实现加载圆形或者圆角图片的需求啦