RoundedBitmapDrawable 实现Bitmap圆角

创建一个正圆形带有边框的图片
private Drawable createRoundImageWithBorder(Bitmap bitmap){
//原图宽度
int bitmapWidth = bitmap.getWidth();
//原图高度
int bitmapHeight = bitmap.getHeight();
//边框宽度 pixel
int borderWidthHalf = 20;

//转换为正方形后的宽高
int bitmapSquareWidth = Math.min(bitmapWidth,bitmapHeight);

//最终图像的宽高
int newBitmapSquareWidth = bitmapSquareWidth+borderWidthHalf;

Bitmap roundedBitmap = Bitmap.createBitmap(newBitmapSquareWidth,newBitmapSquareWidth,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(roundedBitmap);
int x = borderWidthHalf + bitmapSquareWidth - bitmapWidth;
int y = borderWidthHalf + bitmapSquareWidth - bitmapHeight;

//裁剪后图像,注意X,Y要除以2 来进行一个中心裁剪
canvas.drawBitmap(bitmap, x/2, y/2, null);
Paint borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setStrokeWidth(borderWidthHalf);
borderPaint.setColor(Color.WHITE);

//添加边框
canvas.drawCircle(canvas.getWidth()/2, canvas.getWidth()/2, newBitmapSquareWidth/2, borderPaint);

RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(),roundedBitmap);
roundedBitmapDrawable.setGravity(Gravity.CENTER);
roundedBitmapDrawable.setCircular(true);
return roundedBitmapDrawable;

}

作者:李涛丶
链接:https://www.jianshu.com/p/ed42d8c90a45
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容