我正在尝试创建一个在屏幕中间有一个透明孔的黑色屏幕。这是我试过的。

@Override
public void draw(Canvas canvas)
{
    Paint myPaint = new Paint();
    myPaint.setColor(0xC0000000);
    canvas.drawRect(mBlackRect, myPaint);

    myPaint = new Paint();
    myPaint.setColor(Color.TRANSPARENT);
    myPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    canvas.drawRect(mTransparentRect, myPaint);
}

第二种颜色是黑色而不是透明的。我怎样才能在我的半黑画布上打一个透明的洞?

最佳答案

你没有保存画布,请尝试下面的代码

Paint myPaint = new Paint();
    int sc = canvas.saveLayer(mBlackRect.left, mBlackRect.top,
            mBlackRect.right, mBlackRect.bottom, myPaint,
            Canvas.ALL_SAVE_FLAG);
    myPaint.setColor(0xC0000000);
    canvas.drawRect(mBlackRect, myPaint);

    myPaint.setColor(Color.TRANSPARENT);
    myPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    canvas.drawRect(mTransparentRect, myPaint);
    myPaint.setXfermode(null);
    canvas.restoreToCount(sc);

10-04 23:39