以前在eoe論壇中找過裁剪圖片為圓形圖片的方法,但是效果都不是很理想,這幾天因為公司業務的要求,需要對頭像進行裁剪以圓形的方式顯示,這個方法是根據傳入的圖片的高度(height)和寬度(width)決定的,如果是 width <= height時,則會裁剪高度,裁剪的區域是寬度不變高度從頂部到寬度width的長度;如果 width > height,則會裁剪寬度,裁剪的區域是高度不變,寬度是取的圖片寬度的中心區域,不過不同的業務需求,對裁剪圖片要求不一樣,可以根據業務的需求來調整裁剪的區域。
好了,不多說了,直接上代碼
復制代碼 代碼如下:
/**
* 轉換圖片成圓形
* @param bitmap 傳入Bitmap對象
* @return
*/
public Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
if (width <= height) {
roundPx = width / 2;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width,
height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, src, dst, paint);
return output;
}