参考
Android学习笔记(四):android画图之paint之setXfermode
Android之遮罩功能的实现
Android自定义圆形图片
Android 完美实现图片圆角和圆形(对实现进行分析)
一、概念
我们知道 在正常的情况下,在已有的图像上绘图将会在其上面添加一层新的形状。 如果新的Paint是完全不透明的,那么它将完全遮挡住下面的Paint.而setXfermode就可以来解决这个问题
Canvas canvas = new Canvas(bitmap1);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(mask, 0f, 0f, paint);
canvas原有的图片 可以理解为背景 就是dst
新画上去的图片 可以理解为前景 就是src
Paste_Image.png
PorterDuff.Mode.CLEAR 清除画布上图像
PorterDuff.Mode.SRC 显示上层图像
PorterDuff.Mode.DST 显示下层图像
PorterDuff.Mode.SRC_OVER上下层图像都显示,上层居上显示
PorterDuff.Mode.DST_OVER 上下层都显示,下层居上显示
PorterDuff.Mode.SRC_IN 取两层图像交集部门,只显示上层图像
PorterDuff.Mode.DST_IN 取两层图像交集部门,只显示下层图像
PorterDuff.Mode.SRC_OUT 取上层图像非交集部门
PorterDuff.Mode.DST_OUT 取下层图像非交集部门
PorterDuff.Mode.SRC_ATOP 取下层图像非交集部门与上层图像交集部门
PorterDuff.Mode.DST_ATOP 取上层图像非交集部门与下层图像交集部门
PorterDuff.Mode.XOR 取两层图像的非交集部门
二、例子
1、添加资源文件:attrs.xml
2、创建自定义组件MaskImage.java
package com.xzw.mask.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.xzw.mask.R;
public class MaskImage extends ImageView{
int mImageSource=0;
int mMaskSource=0;
RuntimeException mException;
public MaskImage(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MaskImage, 0, 0);
mImageSource = typedArray.getResourceId(R.styleable.MaskImage_image, 0);
mMaskSource = typedArray.getResourceId(R.styleable.MaskImage_mask, 0);
if (mImageSource == 0 || mMaskSource == 0) {
mException = new IllegalArgumentException(typedArray.getPositionDescription() +
": The content attribute is required and must refer to a valid image.");
}
if (mException != null)
throw mException;
/**
* 主要代码实现
*/
//获取图片的资源文件
Bitmap original = BitmapFactory.decodeResource(getResources(), mImageSource);
//获取遮罩层图片
Bitmap mask = BitmapFactory.decodeResource(getResources(), mMaskSource);
Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Config.ARGB_8888);
//将遮罩层的图片放到画布中
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//设置两张图片相交时的模式
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mCanvas.drawBitmap(original, 0, 0, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
setImageBitmap(result);
setScaleType(ScaleType.CENTER);
typedArray.recycle();
}
}
3、在布局文件中添加