如何在屏幕中心创建透明弯曲的透明矩形?

我编写了以下代码,并在屏幕中心为弯曲的矩形添加了alpha,但是显示的是背景色而不是透明度

int width = canvas.getWidth();
int height = canvas.getHeight();
Rect childRect = this.getChildRect();

Paint outerPaint = new Paint();
outerPaint.setColor(Color.LTGRAY);
borderPaint.setStyle(Paint.Style.FILL);


Paint innerPaint = new Paint();
innerPaint.setARGB(0, 0, 0, 0);
innerPaint.setAlpha(0);
innerPaint.setStyle(Paint.Style.FILL);

canvas.drawRect(0.0F, 0.0F, width, height, outerPaint);
canvas.drawRoundRect(new RectF(childRect.left, childRect.top, childRect.right, childRect.bottom), 8F, 8F, innerPaint);

最佳答案

您可以使用绘画的setXfermode()并传递PorterDuff.Mode.ADDPorterDuff.Mode.ADD作为参数以获得内部透明区域,而不是在绘画中添加alpha。

在代码中进行以下更改:

int width = canvas.getWidth();
int height = canvas.getHeight();
Rect childRect = this.getChildRect();

Paint outerPaint = new Paint();
outerPaint.setColor(Color.LTGRAY);
outerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
outerPaint.setAntiAlias(true);

Paint innerPaint = new Paint();
innerPaint.setColor(Color.TRANSPARENT);
innerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
innerPaint.setAntiAlias(true);

canvas.drawRect(0.0F, 0.0F, width, height, outerPaint);
canvas.drawRoundRect(new RectF(childRect.left, childRect.top, childRect.right, childRect.bottom), 8F, 8F, innerPaint);

09-10 14:22