您的位置:首页 > 其它

两种实现CircleImageView的方式

2017-06-04 22:01 323 查看

使用Paint.setXferMode

参考链接: 转自博客,请点击此处

要想事项CircleImageView,分成两部分:

创建圆形bitmap

使用canvas画bitmap

创建圆形bitmap

private Bitmap createRoundConerImage(Bitmap source)
{
final Paint paint = new Paint();
paint.setAntiAlias(true);
//创建一个相同大小的bitmap对象
Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888);
//封装成Canvas对象
Canvas canvas = new Canvas(target);
RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
//通过canvas画圆形,变为圆形画布
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
//设置画笔的叠加方式
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//将原图片画在画布上
canvas.drawBitmap(source, 0, 0, paint);
//取出bitmap对象
return target;
}


画生成的圆形bitmap对象

在onDraw(Canvas canvas)中添加:

canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);


使用Shader

参考链接:http://blog.csdn.net/lmj623565791/article/details/41967509

将drawable变为bitmap

将bitmap通过BitmapShader关联到Paint

通过paint对象去在canvas对象上drawCircle

将drawable对象变为bitmap

public Bitmap drawable2bitmap(Drawable drawable){
if(drawable == null){
retrurn null;
}
if(drawable instanceof BitampDrawable){
retrun ((BitampDrawble)drawable).getBitmap();
}
int w = drawble.getIntrisicWidth();
int h = drawble.getIntrisicHeight();
Bitmap newBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
drawable.setBounds(0,0,w,h);
drawable.draw(Canvas);
return newBitamp;
}


将bitmapshader和要展示的bitmap进行关联

mMatrix.setScale(scale,scale);//设置放大的倍数
mBitmapShader.setLocalMatrix(mMatrix);

BitmapShader mBitmapShader = new BitmapShader(newBitmap,TileMode.CLAMP,TileMode.CLAMP);
mBitmapPaint.setShader(mBitmapShader);


再进行画圆

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  canvas Circle ImageView