PorterDuffXfermode實現刮刮卡效果
阿新 • • 發佈:2019-01-28
//自定義view繼承view
public class XfermodeView extends View { private Context context; private Path path; private Canvas mcanvas; private Paint mpanit; private Bitmap bgBitmap; private Bitmap fgBitmap; public XfermodeView(Context context) { this(context, null); } public XfermodeView(Context context, AttributeSet attrs) { super(context, attrs); // this.context=context; initView(); } private void initView() { mpanit = new Paint(); mpanit.setAlpha(0);//透明度設定為0顯示檫除效果, //portduff進行圖層混合時也會計算透明通道的值,混合後會顯示底層的圖片 mpanit.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); //使用dis_in模式將路徑繪製到到前面覆蓋的圖層上面 mpanit.setStyle(Paint.Style.STROKE); mpanit.setStrokeWidth(50); mpanit.setStrokeCap(Paint.Cap.ROUND);//讓筆觸連線處圓滑 mpanit.setStrokeJoin(Paint.Join.ROUND);//讓筆觸連線處圓滑 path = new Path(); bgBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.lock_screen_houma);//設定背景圖片 fgBitmap = Bitmap.createBitmap(bgBitmap.getWidth(), bgBitmap.getHeight(), Bitmap.Config.ARGB_8888); mcanvas = new Canvas(fgBitmap);//根據背景圖片繪製灰色區域 mcanvas.drawColor(Color.GRAY);//設定畫布顏色 } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: path.reset(); path.moveTo(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE: path.lineTo(event.getX(), event.getY());//繪製線條 break; } mcanvas.drawPath(path, mpanit); invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(bgBitmap,0,0,null);//預設畫筆繪製背景 canvas.drawBitmap(fgBitmap,0,0,null);//繪製灰色區域 }
}