给选定的图片加一个遮罩层,只显示绘制的圆形区域,其它部分透明,
但控件大小还是原图尺寸,
这种剪切模式仅适用于bitmap的绘制,直接用canvas绘制的形状不可以用。(形状和bitmap混用也可以)
classCommViewextendsView{
privatePaintmPaint;
publicCommView(Contextcontext){
super(context);
setFocusable(true);
mPaint=newPaint();
mPaint.setAntiAlias(true);
}
protectedvoidonDraw(Canvascanvas){
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);//设画布白色
canvas.translate(20,20);//移动画布
//原始图片
Bitmapsrc=BitmapFactory.decodeResource(getResources(),R.drawable.aaa);
intwidth=src.getWidth();
intheigh=src.getHeight();
//图片的遮罩(搞一个和原图一样大的空白bitmap)
Bitmapmask=Bitmap.createBitmap(width,heigh,src.getConfig());
Canvascc=newCanvas(mask);
cc.drawCircle(width/2,heigh/2,width/2-10,mPaint);
/*
*离屏缓存
*Layer层的宽和高要设定好,不然会出现有些部位不再层里面,你的操作是不对这些部位起作用的
*/
intsc=canvas.saveLayer(0,0,width,heigh,null,Canvas.ALL_SAVE_FLAG);
//先绘制dis目标图
canvas.drawBitmap(src,0,0,mPaint);
//设置混合模式(只在源图像和目标图像相交的地方绘制目标图像)
mPaint.setXfermode(newPorterDuffXfermode(PorterDuff.Mode.DST_IN));
//再绘制src源图
canvas.drawBitmap(mask,0,0,mPaint);
//还原混合模式
mPaint.setXfermode(null);
//还原画布
canvas.restoreToCount(sc);
}
}
下面是更简单的方法,直接裁剪canvas为圆形
/**
* 圆形imageview
* Created by wwf on 2017/4/7.
*/
@SuppressLint("AppCompatCustomView")
public class CircleImageView extends ImageView {
int radio;
public CircleImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
protected void onDraw(Canvas canvas) {
radio = getWidth() < getHeight() ? getWidth()/2 : getHeight()/2;
Path path = new Path();
path.addCircle(getWidth()/2, getHeight()/2, radio, Path.Direction.CCW);
canvas.clipPath(path, Region.Op.INTERSECT);
super.onDraw(canvas);
}
}