我们都知道,刮刮卡有2个图层,即上面用来被刮掉的图层和下面隐藏的图层,初始状态下,上面的图层会将下面的图层覆盖,当用手刮上面的图层时, 下面的图层会显示出来。我们使用PorterDuffXfermode来实现这个效果。
/** * Created by admin on 2018-01-22 */ public class XferModeView extends View{ private Bitmap mBgBitmap ,mFgBitmap; private Paint mPaint; private Canvas mCanvas; private Path mPath; public XferModeView(Context context) { super(context); } public XferModeView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private void init() { 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.mipmap.ic_launcher); mFgBitmap = Bitmap.createBitmap(mBgBitmap.getWidth(),mBgBitmap.getWidth(), Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mFgBitmap); mCanvas.drawColor(Color.GRAY); } //Path 保存用户滑过的路径 @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: mPath.reset(); mPath.moveTo(event.getX(),event.getY()); break; case MotionEvent.ACTION_MOVE: mPath.lineTo(event.getX(),event.getY()); 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); }