我仍然不完全确定你想要完成什么。您显示的形状可以绘制如下:
// set up some constants
int w = canvas.getWidth();
int h = canvas.getHeight();
RectF rect = new RectF(100, 100, w - 100, h - 100);
float radius = 10.0f; // should be retrieved from resources and defined as dp
float borderWidth = 2.0f; // ditto
int innerRectFillColor = 0x33000000; // or whatever shade it should be
// first fill the interior
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(innerRectFillColor);
paint.setStyle(Paint.Style.FILL);
canvas.drawRoundRect(rect, radius, radius, paint);
// then draw the border
paint.setColor(Color.WHITE);
paint.setStrokeWidth(borderWidth);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRoundRect(rect, radius, radius, paint);
相反,如果您想在孔周围绘制(以便背景显示出来),则绘制周围矩形的技巧将不起作用,因为圆角(边框也使其变得更加复杂)。相反,您可以创建一个单独的Bitmap
有一个透明的孔,然后绘制它。您需要使用 Porter-Duff 传输模式CLEAR
在位图中打孔:
// same constants as above except innerRectFillColor is not used. Instead:
int outerFillColor = 0x77000000;
// first create an off-screen bitmap and its canvas
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas auxCanvas = new Canvas(bitmap);
// then fill the bitmap with the desired outside color
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(outerFillColor);
paint.setStyle(Paint.Style.FILL);
auxCanvas.drawPaint(paint);
// then punch a transparent hole in the shape of the rect
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
auxCanvas.drawRoundRect(rect, radius, radius, paint);
// then draw the white rect border (being sure to get rid of the xfer mode!)
paint.setXfermode(null);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
auxCanvas.drawRoundRect(rect, radius, radius, paint);
// finally, draw the whole thing to the original canvas
canvas.drawBitmap(bitmap, 0, 0, paint);