自定义View之将图片裁剪成圆形图片
使用PorterDuffXfermode方式来实现
在使用这中方式之前,我们有必要弄清楚PorterBuddx
究竟是什么。
简单来说,他是定义的一种图像融合的方式,具体的模式有如下几种,效果如图:
在次,不多做介绍,想深入了解PorterDuffXfermode
可以参考各个击破搞明白PorterDuff.Mode
本次使用mode是SRCIN
,由图效果可知,我们需要在原图上绘制一个圆,原图与我们绘制得圆重叠得区域就会显示出来,原理很简单,下面开始代码实现:
public class CircleImageView1 extends ImageView {
private Paint mPaint;
private Shape mShape;
private float mRadius;
private float[] outerRadii = new float[8];;
public CircleImageView1(Context context) {
this(context,null);
}
public CircleImageView1(Context context, @Nullable AttributeSet attrs) {
this(context,attrs,0);
}
public CircleImageView1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
setLayerType(LAYER_TYPE_HARDWARE,null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.BLACK);
//注意这里,将画笔的PorterDuffXfermode模式设置为了DST_IN模式!!!
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int min = Math.min(width,height);
mRadius = min/2;
setMeasuredDimension(min,min);
//因为是圆,所以要设置为长宽相等
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed){
if (mShape ==