我们时常会用到圆形图片,那么,是对图片进行裁剪,还是自定义圆形的ImageView,如果没有特殊要求的话,我们肯定选择前者,原因很简单,因为简单!!直接上源码,就是这么粗暴任性~~~
/**
* 将图片剪裁为圆形
*/
public static Bitmap createCircleImage(Bitmap source) {
int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawCircle(length / 2, length / 2, length / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
只需要输入bitmap,然后就给你返回圆形的bitmap,然后设置到ImageView中,是不是很简单。
这里另外提一点,如果从ImageView中拿出来bitmap,只需要一行代码:
//从ImageView中获取bitmap
Bitmap bm =((BitmapDrawable) ( imageView).getDrawable()).getBitmap();