Android圆角图片
相比较于iOS实现圆角图片,Android的方式还是复杂些???
参考How to make an ImageView with rounded corners?
1.绘制圆角矩形,在绘制bitmap,通过设置setXfermode
为SRC_IN
来实现
setXfermode
相关解释可参考HenCoder Android 开发进阶: 自定义 View 1-2 Paint 详解
如下的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.facebook);
mImageView.setImageBitmap(getRoundedCornerBitmap(bitmap, 100));
}
private Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
RectF rectF = new RectF(rect);
float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.RED);//颜色随便设?
canvas.drawRoundRect(rectF, roundPx , roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}