利用PorterDuffXfermode實現,圖例如下旺遮,需要注意的是顿痪,PorterDuffXfermode設置的是兩個圖層交集區(qū)域的顯示方式,dst是先畫的圖形痛阻,src是后畫的圖形菌瘪。
其中最常用的就是通過DST_IN,SRC_IN模式來實現將一個矩形圖片編程圓角圖片或者圓形圖片的效果。先利用一個普通畫筆畫一個Mask遮罩層阱当,再用帶PorterDuffXfermode的畫筆講圖像畫在遮罩層上麻车,這樣就可以通過上面所說的效果來混合兩個圖像了缀皱。
mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.test);
mOut = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mOut);
paint = new Paint();
paint.setAntiAlias(true);
canvas.drawRoundRect(0, 0, mBitmap.getWidth(), mBitmap.getHeight(), 80, 80, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(mBitmap,0,0,paint);
下面實現刮刮卡效果斗这,如下圖
完整代碼如下:
package com.example.administrator.myapplication;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by Administrator on 2015/11/25 0025.
*/
public class XfermodeView extends View {
Bitmap mBgBitmap,mFgBitmap;
Paint mPaint;
Canvas mCanvas;
Path mPath;
public XfermodeView(Context context) {
super(context);
init();
}
public XfermodeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/*
* 讓它的筆觸和連接處能更加圓滑一點动猬,即Paint.Join.ROUND和Paint.Cap.ROUND屬性
* 最關鍵的一步是:需要將畫筆的透明度設置為0,這樣才能顯示出擦除的效果表箭,因為在使用PorterDuffXfermode進行圖層混合時赁咙,并不是簡單地進行圖層的計算,同時也會去計算透明度通道的值
*
*/
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.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 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);
}
}