在开发中,为了让图片效果美观,有时需要对图片做一些处理。圆角就是一种常用的效果处理。对于图片做圆角处理的方法很多,下面从绘制的角度做简单介绍,主要代码如下:
public Bitmap getRoundedCornerBitmap(Bitmap sourceBitmap) {
try {
Bitmap targetBitmap = Bitmap.createBitmap(sourceBitmap.getWidth(), sourceBitmap.getHeight(), Config.ARGB_8888);
// 得到画布
Canvas canvas = new Canvas(targetBitmap);
// 创建画笔
Paint paint = new Paint();
paint.setAntiAlias(true);
// 值越大角度越明显
float roundPx = 30;
float roundPy = 30;
Rect rect = new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight());
RectF rectF = new RectF(rect);
// 绘制
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectF, roundPx, roundPy, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sourceBitmap, rect, rect, paint);
return targetBitmap;
} catch (Exception e) {
e.printStackTrace();
} catch (Error e) {
e.printStackTrace();
}
return null;
}
使用方法比较简单:
ImageView image = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
image.setImageBitmap(getRoundedCornerBitmap(bitmap));
// 回收Bitmap资源
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
bitmap = null;
}