画笔要使用PorterDuffXfermode,这个是设置两个图层交集区域的显示方式,dest是先画的图形,sec是后画的图形。
自定义刮刮卡View的代码
public class XfermodeView extends View {
private Bitmap mBgBitmap, mFgBitmap;
private Paint mPaint;
private Canvas mCanvas;
private Path mPath;
public XfermodeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
//这个画笔设置透明度为0就是为了显示底层图,起到擦除效果。
mPaint = new Paint();
mPaint.setAlpha(0);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeWidth(50);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPath = new Path();
mBgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
mFgBitmap = Bitmap.createBitmap(mBgBitmap.getWidth(), mBgBitmap.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mFgBitmap);
mCanvas.drawColor(Color.GRAY);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case ACTION_DOWN:
mPath.reset();
mPath.moveTo(event.getX(), event.getY());
break;
case ACTION_MOVE:
mPath.lineTo(event.getX(),event.getY());
break;
case ACTION_UP:
break;
}
mCanvas.drawPath(mPath,mPaint);
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBgBitmap,0,0,null);
canvas.drawBitmap(mFgBitmap,0,0,null);
}
}
显示的Activity布局代码
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CH6.section7.XfermodeViewActivity">
<wangsheng.swpuiot.qunyingzhuan.CH6.section7.XfermodeView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
效果图