1. 问题背景
设计的需要是这样的:需要上边两个角圆角,下边两个角是直角,同时这张图是Url Glide加载进来的。OK,目标明确,做起来也不是很难了。
2. 解决方案
- 首先加载 Url 图片进来
Glide.with(this).load(url).into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
Bitmap source = ((BitmapDrawable) resource).getBitmap();
imageView.setImageBitmap(getRoundBitmap(source
, ltCornerSize, rtCornerSize, rbCornerSize, lbCornerSize));
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
- getRoundBitmap 方法实现,这里我们是用 Canvas + Paint + Path 来绘制的,Code 如下:
/**
* 为 Bitmap 设置切割圆角
*
* @param source 原图片
* @param lt 左上圆角 px
* @param rt 右上圆角 px
* @param rb 右下圆角 px
* @param lb 左下圆角 px
* @return 按照参数切割圆角后的 Bitmap
*/
public static Bitmap getRoundBitmap(Bitmap source, float lt, float rt, float rb, float lb) {
Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setAntiAlias(true);
// 设置画笔为原图
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
float width = source.getWidth(), height = source.getHeight();
// 绘制四个圆角,只四个圆角的话,结果如图1
canvas.drawArc(new RectF(0, 0, lt, lt), 180, 90, true, paint);
canvas.drawArc(new RectF(width - rt, 0, width, rt), 270, 90, true, paint);
canvas.drawArc(new RectF(width - rb, height - rb, width, height), 0, 90, true, paint);
canvas.drawArc(new RectF(0, height - lb, lb, height), 90, 90, true, paint);
// 绘制剩余区域
// 因为上边是圆角,我们只绘制了一个半径,所以除2就是剩余要绘制的区域了
// 不除2的话,结果如图2
lt /= 2;
rt /= 2;
rb /= 2;
lb /= 2;
Path path = new Path();
path.moveTo(0, lt);
path.moveTo(lt, lt);
path.moveTo(lt, 0);
path.lineTo(width - rt, 0);
path.lineTo(width - rt, rt);
path.lineTo(width, rt);
path.lineTo(width, height - rb);
path.lineTo(width - rb, height - rb);
path.lineTo(width - rb, height);
path.lineTo(lb, height);
path.lineTo(lb, height - lb);
path.lineTo(0, height - lb);
path.lineTo(0, lt);
path.close();
canvas.drawPath(path, paint);
return result;
}
例图1 例图2,乱七八糟……
3. End
最终的结果是这样事儿的: OK 修改一下参数,交工!
|