Canvas画圆有两种常见的实现方法:
-
画图重叠取相交
- 渲染画圆
画图重叠取相交
如图下的第一张ImageView中,其实是画了一个为背景图的方形,另一个是蓝色颜色的圆。通过Mode.SRC_IN设置相交模式,可得第三张ImageView的圆形图片。
代码:
public Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / 2;
left = 0;
top = 0;
right = width;
bottom = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffff0000;
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
paint.setAntiAlias(true);// 设置画笔无锯齿
canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas
paint.setColor(Color.BLUE);
canvas.drawCircle(roundPx, roundPx, roundPx, paint);//A绘图(圆形)
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
canvas.drawBitmap(bitmap, src, dst, paint); //B绘图(正方形以图片为背景) 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle
return output;
}
此时方形的图片已经被处理为圆形,在ImageView.setImageBitmap(toRoundBiamap())即可实现。
注意:如果将代码中的A和B相互调换下,SRC_IN无效。
无效图: