我想在灰色方块位图上检测到手指的区域进行擦除但不起作用。
我用ic_launch作为图像显示一个位图,然后我在图像上显示一个灰色方形油漆,我可以将颜色修改为TRANSPARENT
有什么问题?谢谢
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Paint mPaint;
public CaseView(Context c) {
super(c);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(40);
mBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
mBitmap.setPixel(i, j, Color.GRAY);
}
}
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(0, 0, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(100, 100, 200, 200, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
Bitmap _scratch = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
canvas.drawColor(Color.WHITE);
// logo
canvas.drawBitmap(_scratch, 0, 100, null);
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
if ((mX < 100 && mX >= 0) && (mY < 100 && mY >= 0)) {
mBitmap.setPixel((int) mY,(int) mX, Color.TRANSPARENT);
}
}
}
canvas.drawBitmap(mBitmap, 0, 100, mBitmapPaint);
Bitmap mutableBitmap = Bitmap.createBitmap(_scratch.getWidth(),
_scratch.getHeight(), Bitmap.Config.ARGB_8888);
mutableBitmap.setPixel(50, 50, 124);
canvas.drawBitmap(mutableBitmap, 0, 100, null);
int pixelColor = mBitmap.getPixel(50, 50);
int red = Color.red(pixelColor);
int green = Color.green(pixelColor);
Log.v("red", "red:" + red + " /green:" + green);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
Log.v("onTouchEvent", "x:" + x + "/y:" + y);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
答案 0 :(得分:5)
对于绘图,您需要使用一个Paint类绘制路径。但是为了再次擦除,你必须在你的触摸坐标上绘制一条路径
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
在 android-sdk 示例中,他们提供了一个 FingerPaint 类,可以很好地解释它