我嘗試使用Porter-Duff Xfermodes擦除Android應用程序中的位圖部分。使用PorterDuff模式擦除位圖部件
我有一個藍色的位圖疊加的綠色背景。當我觸摸屏幕時,應該創建覆蓋位圖中的「洞」,使綠色背景可見。而不是一個洞,我現在的代碼產生一個黑點。
以下是我的代碼。任何想法,我在這裏做錯了什麼?
/** 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, Bitmap.Config.RGB_565);
bitmapCanvas = new Canvas();
bitmapCanvas.setBitmap(bitmap);
bitmapCanvas.drawColor(Color.BLUE);
// Set eraser paint properties
eraserPaint.setAlpha(0);
eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
eraserPaint.setAntiAlias(true);
}
@Override
public void onDraw(Canvas canvas) {
bitmapCanvas.drawColor(Color.BLUE);
bitmapCanvas.drawCircle(x, y, 10, eraserPaint);
canvas.drawBitmap(bitmap, 0, 0, paint);
}
public boolean onTouch(View view, MotionEvent event) {
x = (int) event.getX();
y = (int) event.getY();
invalidate();
return true;
}
}
非常感謝喬希!使用Bitmap.Config.ARGB_8888而不是Bitmap.Config.RGB_565創建位圖解決了這個問題。 關於效果:我計劃將繪製路徑的alpha作爲下一步應用到我的前景位圖。你會建議採用什麼方法,而不是使用Porter-Duff關於繪圖性能? – Philipp 2010-08-13 09:18:04
1.當您在onTouch中獲得觸摸事件時,不時使用drawPath爲透明圖像繪製黑色路徑。這是你的橡皮擦位圖。如果你還沒有這樣做,API演示中的FingerPaint應用程序有一些很好的示例代碼。 2.在onDraw中,使用適當的PorterDuff方法將您的橡皮擦位圖應用於原始藍色位圖。這會將藍色位圖中的整體切割爲您已擦除的內容(黑色路徑)。 3.仍然在onDraw中,將綠色位圖放在屏幕上,然後是新剪下的藍色位圖。 – Josh 2010-08-13 14:57:57
請注意,上述操作可能會在每個繪製週期中花費很高 - 查看裁剪區域以將您正在更新的區域限制爲僅在用戶在橡皮擦位圖中更改的區域。 – Josh 2010-08-13 14:58:58