橡皮擦效果.gif
SRC_OUT模式和SRC_IN相反,相对位置,目标像素的透明度越高,原像素的透明度越低,目标像素不透明,则原像素透明,利用这个可以实现橡皮擦效果
定义一些变量
private Bitmap bitmapSrc;
//path的paint
private Paint mPathPaint = new Paint();
private Paint mPaint = new Paint();
private Bitmap bitmapDst;
//手势轨迹
private Path path = new Path();
//目标画布
private Canvas canvasDst;
初始化参数,创建和原图片相同宽高的透明bitmap
public RubberView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setLayerType(LAYER_TYPE_SOFTWARE,null);
bitmapSrc = BitmapFactory.decodeResource(getResources(), R.mipmap.xyjy6);
//利用SRC_OUT使用透明的白底图片
Bitmap.Config config = Bitmap.Config.ARGB_8888;
bitmapDst = Bitmap.createBitmap(bitmapSrc.getWidth(), bitmapSrc.getHeight(), config);
canvasDst = new Canvas(bitmapDst);
//利用SRC_OUT使用不透明的颜色来描绘手势移动
mPathPaint.setColor(Color.WHITE);
//橡皮擦大小
mPathPaint.setStrokeWidth(30);
mPathPaint.setStyle(Paint.Style.STROKE);
mPathPaint.setStrokeCap(Paint.Cap.ROUND);
}
在onTouchEvent事件中记录手指移动轨迹
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
path.moveTo(event.getX(),event.getY());
postInvalidate();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(event.getX(),event.getY());
postInvalidate();
break;
}
return false;
}
在onDraw方法中进行处理
@Override
protected void onDraw(Canvas canvas) {
//在目标画布上画手势轨迹
canvasDst.drawPath(path,mPathPaint);
canvas.drawBitmap(bitmapDst,0,0, mPaint);
Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT);
mPaint.setXfermode(xfermode);
canvas.drawBitmap(bitmapSrc, 0, 0, mPaint);
mPaint.setXfermode(null);
}
网友评论