网上很多将图片转化成圆形图并且加上不同颜色的边框都是重写imageview的方式来进行实现,虽然重写后,自定义的控件好,任你改变,但是,无形中就增加了代码量,不同的类也增加了。所以,如果可以设法写一个工具类来实现的化就再好不过了。
不多说,直接上源码:
public static final int TWO=2;
/*
* 将任意图片转化指定半径的圆形图--最好是正方形 bmp 代表图片 radius 半径
*/
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap scaledSrcBmp;
int diameter = radius * TWO;
// 为了防止宽高不相等,造成圆形图片变形,因此截取长方形中处于中间位置最大的正方形图片
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
int squareWidth = 0, squareHeight = 0;
int x = 0, y = 0;
Bitmap squareBitmap;
if (bmpHeight > bmpWidth) {// 高大于宽
squareWidth = squareHeight = bmpWidth;
x = 0;
y = (bmpHeight - bmpWidth) / TWO;
// 截取正方形图片
squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
squareHeight);
} else if (bmpHeight < bmpWidth) {// 宽大于高
squareWidth = squareHeight = bmpHeight;
x = (bmpWidth - bmpHeight) / TWO;
y = 0;
squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
squareHeight);
} else {
squareBitmap = bmp;
}
if (squareBitmap.getWidth() != diameter
|| squareBitmap.getHeight() != diameter) {
scaledSrcBmp = Bitmap.createScaledBitmap(squareBitmap, diameter,
diameter, true);
} else {
scaledSrcBmp = squareBitmap;
}
Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(),
scaledSrcBmp.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(),
scaledSrcBmp.getHeight());
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(scaledSrcBmp.getWidth() / TWO,
scaledSrcBmp.getHeight() / TWO, scaledSrcBmp.getWidth() / TWO,
paint);
//设置图形重叠时的处理方式
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(scaledSrcBmp, rect, rect, paint);
// bitmap回收(recycle导致在布局文件XML看不到效果)
bmp.recycle();
squareBitmap.recycle();
scaledSrcBmp.recycle();
//添加边框
setBitmapBorder(canvas);
bmp = null;
squareBitmap = null;
scaledSrcBmp = null;
return output;
}
/*
* 为圆形图添加边框
*/
public static void setBitmapBorder(Canvas canvas) {
// 1.获取Canvas裁剪界限:
Rect rect = canvas.getClipBounds();
int width = rect.width();
int height = rect.height();
Paint paint = new Paint();
// 设置边框颜色
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
// 设置边框宽度
paint.setStrokeWidth(TWO);
// 加入效果
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
//第一,第二个参数确定位置,第三个参数是半径,第四个是画笔
canvas.drawCircle(width / TWO, height / TWO, (width- TWO)/TWO, paint);
}
刚开始设想写在一起,不过你会发现,在变为圆形的时候,是用重叠的方法变为圆,所以边框就会无形地被遮掉了。所以要先得到圆形的bitmap,然后再增加边框。
参考资料:
http://blog.csdn.net/spring_he/article/details/14448537--变圆形图
http://www.cnblogs.com/tony-yang-flutter/p/3559866.html--加边框
http://www.cnblogs.com/lqminn/archive/2012/11/30/2796101.html--paint类知识补充
http://blog.csdn.net/linfeng24/article/details/21340187--重写imageview进行变圆