Glide使用CircleCrop
即可加載圓形圖片,有時需求需要給圖片加上一層白色描邊:
復(fù)制一份TransformationUtils
夜惭,修改circleCrop()
方法,
// 描邊畫筆铛绰。
private static final Paint CIRCLE_CROP_WHITE_PAINT;
private static final int STROKE_WIDTH = 3;
static {
// 這是Glide源碼诈茧。
CIRCLE_CROP_BITMAP_PAINT = new Paint(CIRCLE_CROP_PAINT_FLAGS);
CIRCLE_CROP_BITMAP_PAINT.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// 描邊畫筆初始化。
CIRCLE_CROP_WHITE_PAINT = new Paint(CIRCLE_CROP_PAINT_FLAGS);
CIRCLE_CROP_WHITE_PAINT.setColor(Color.WHITE);
CIRCLE_CROP_WHITE_PAINT.setStyle(Paint.Style.STROKE);
CIRCLE_CROP_WHITE_PAINT.setAntiAlias(true);
CIRCLE_CROP_WHITE_PAINT.setStrokeWidth(STROKE_WIDTH);
//CIRCLE_CROP_WHITE_PAINT.setStrokeCap(Paint.Cap.ROUND);
CIRCLE_CROP_WHITE_PAINT.setDither(true);
}
public static Bitmap circleCrop(@NonNull BitmapPool pool, @NonNull Bitmap inBitmap,
int destWidth, int destHeight) {
int destMinEdge = Math.min(destWidth, destHeight);
float radius = destMinEdge / 2f;
int srcWidth = inBitmap.getWidth();
int srcHeight = inBitmap.getHeight();
float scaleX = destMinEdge / (float) srcWidth;
float scaleY = destMinEdge / (float) srcHeight;
float maxScale = Math.max(scaleX, scaleY);
float scaledWidth = maxScale * srcWidth;
float scaledHeight = maxScale * srcHeight;
float left = (destMinEdge - scaledWidth) / 2f;
float top = (destMinEdge - scaledHeight) / 2f;
RectF destRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
// Alpha is required for this transformation.
Bitmap toTransform = getAlphaSafeBitmap(pool, inBitmap);
Bitmap.Config outConfig = getAlphaSafeConfig(inBitmap);
Bitmap result = pool.get(destMinEdge, destMinEdge, outConfig);
result.setHasAlpha(true);
BITMAP_DRAWABLE_LOCK.lock();
try {
Canvas canvas = new Canvas(result);
// Draw a circle
canvas.drawCircle(radius, radius, radius, CIRCLE_CROP_SHAPE_PAINT);
// Draw the bitmap in the circle
canvas.drawBitmap(toTransform, null, destRect, CIRCLE_CROP_BITMAP_PAINT);
// Draw a white
/************************描邊*********************/
float borderRadius = radius - (STROKE_WIDTH / 2);
canvas.drawCircle(radius, radius, borderRadius, CIRCLE_CROP_WHITE_PAINT);
/************************描邊*********************/
clear(canvas);
} finally {
BITMAP_DRAWABLE_LOCK.unlock();
}
if (!toTransform.equals(inBitmap)) {
pool.put(toTransform);
}
return result;
}
public class CircleCropWhite extends CircleCrop {
@Override
protected Bitmap transform(
@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
return TransformationUtils.circleCrop(pool, toTransform, outWidth, outHeight);
}
}
使用:
GlideApp.with(context)
.load(image_url)
.transforms(new CircleCropWhite())
.into(image_view);