这个效果主要还是涉及到前面提到的,关于交叉模式的知识点。
首先,需要实现这个效果,就必然要绘制3个图层,最底部是刮出来之后的图片,上面的图层是灰色背景,用来覆盖刮奖区域。还有一个图层就是在我们刮得时候,覆盖在灰色图层上的效果。
public class CustomView extends View {
private Paint mPaint;
private Bitmap bgBitmap,fgBitmpa;
private Path mPath;
private Canvas mCanvas;
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAlpha(0);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(50);
mPaint.setAntiAlias(true);
//让笔触和连接处更加圆滑
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//设置交叉模式
mPath = new Path();
//通过图片得到bitmap对象
bgBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.wallet_logo);
//创建一个bgBitmap的副本
fgBitmpa = Bitmap.createBitmap(bgBitmap.getWidth(), bgBitmap.getHeight(), Bitmap.Config.ARGB_8888);
//创建一个canvas并关联到fgBitmap
mCanvas = new Canvas(fgBitmpa);
//在canvas上绘制灰色背景,并且会关联到fgBitmap上
mCanvas.drawColor(Color.GRAY);
}
@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) {
super.onDraw(canvas);
canvas.drawBitmap(bgBitmap, 0, 0, null);
canvas.drawBitmap(fgBitmpa, 0, 0, null);
}
}
代码比较简单,最关键的地方,就是在onTouchEvent()方法中,通过path距离手指滑动的路线,然后调用drawPath()方法绘制路线,由于交叉模式是取交集,并且paint是透明色的,所以就会把灰色图层绘制成透明。