消しゴム効果の実現
3537 ワード
くだらないことは言わないで、直接コードを貼って、みんなに役に立つことを望んでいます.
public class DrawView extends View{
private Canvas pcanvas;
private Paint paint;
private Path path;
private Bitmap originBitmap;
private Bitmap pureBitmp;
private Bitmap bitmapBuff;
private float scaleWidth;
private float scaleHeight;
private float downx = 0,downy = 0;
public DrawView(Context context) {
super(context);
setBackgroundResource(R.drawable.pic);
path = new Path();
paint = new Paint();
paint.setAlpha(0);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
paint.setAntiAlias(true);
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(15.6f);
initLayer(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
canvas.drawBitmap(bitmapBuff, 0, 0, null);
}
private void initLayer(Context context){
InputStream stream = context.getResources().openRawResource(R.drawable.layer);
originBitmap = BitmapFactory.decodeStream(stream);
int width = originBitmap.getWidth();
int height = originBitmap.getHeight();
Display currentDisplay = ((Activity)context).getWindowManager().getDefaultDisplay();
float newWidth = currentDisplay.getWidth();
float newHeight = currentDisplay.getHeight();
scaleWidth = ((float) newWidth / width);
scaleHeight = ((float) newHeight / height);
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
pureBitmp = Bitmap.createBitmap(originBitmap, 0, 0, width, height,matrix, true);
bitmapBuff = Bitmap.createBitmap(pureBitmp.getWidth(),pureBitmp.getHeight(), Bitmap.Config.ARGB_8888);
pcanvas = new Canvas(bitmapBuff);
pcanvas.drawBitmap(pureBitmp, 0, 0, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
path.reset();
path.moveTo(downx, downy);
break;
case MotionEvent.ACTION_MOVE:
float upx = event.getX();
float upy = event.getY();
touchMove(upx, upy);
invalidate();
break;
case MotionEvent.ACTION_UP:
pcanvas.drawPath(path, paint);
path.reset();
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
private void touchMove(float upx, float upy){
float dx = Math.abs(downx-upx);
float dy = Math.abs(downy-upy);
if (dx >= 4 || dy >= 4) {
path.quadTo(downx, downy, (downx + upx)/2, (downy + upy)/2);
downx = upx;
downy = upy;
}
}
}