我尝试使用Porter-Duff Xfermodes在我的Android应用程序中擦除部分位图.
我有一个绿色背景,由蓝色位图覆盖.当我触摸屏幕时,应该创建覆盖位图中的"洞",使绿色背景可见.而不是一个洞,我当前的代码产生一个黑点.
以下是我的代码.任何想法,我在这里做错了什么?
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new DrawView(this));
}
public class DrawView extends View implements OnTouchListener {
private int x = 0;
private int y = 0;
Bitmap bitmap;
Canvas bitmapCanvas;
private final Paint paint = new Paint();
private final Paint eraserPaint = new Paint();
public DrawView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
// Set background
this.setBackgroundColor(Color.GREEN);
// Set bitmap
bitmap = Bitmap.createBitmap(320, 480, …Run Code Online (Sandbox Code Playgroud) 我试图在自定义视图的onDraw方法中绘制这样的形状.
不幸的是,我无法"剪切"画布上的透明圆圈(通过绘制带有Color.Transparent的圆圈).
我应该先在另一个位图中绘制形状,然后在onDraw提供的画布上绘制它吗?或者这是一种更好(更简单)的方法吗?

这是我尝试的代码(与Color.WHITE一起使用):
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.TRANSPARENT);
mPaint.setStrokeWidth(4);
mPaint.setStyle(Style.STROKE);
canvas.drawColor(getResources().getColor(R.color.black_overlay));
canvas.drawCircle(-3*(this.getBottom()-this.getTop())/4, (this.getTop()+this.getBottom())/2, this.getBottom()-this.getTop(), mPaint);
Run Code Online (Sandbox Code Playgroud)
PS:使用Color.WHITE时,我得到了我想要的确切形状:

解
@Override
public void onDraw(Canvas canvas)
{
mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(getResources().getColor(R.color.black_overlay));
mCanvas.drawCircle(-3*(getHeight())/4, (getHeight())/2, getHeight(), mPaint);
canvas.drawBitmap(mBitmap, 0, 0, null);
}
with
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStrokeWidth(4);
mPaint.setStyle(Style.STROKE);
mPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
Run Code Online (Sandbox Code Playgroud)
注意:createBitamp和新画布应该移出onDraw方法.