利用PorterDuffXfermode实现,图例如下,需要注意的是,PorterDuffXfermode设置的是两个图层交集区域的显示方式,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);
}
}
网友评论