简单的设置圆形按钮

开始的时候,我们先将控件实例化出来,然后将它设置一个图片给它:(记住是bitmap型的)
img = (ImageView) findViewById(R.id.imgHead);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.header1);
Bitmap output = getRoundedCornerBitmap(bitmap);
img.setImageBitmap(output);
以上的代码是设置我的头像为圆形的,以前找了好久,才知道,一句代码就ok啦!好吧,我
又想错了,其实还是需要很多的代码,这里还需要一个方法,里面才是实现圆形的核心代码。

/**
* 圆形头像
*
* @param bitmap
* @param ratio
* 按照截取比例来获取圆形图片
* @return
*/
public Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.gui);
}
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(outBitmap);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPX = bitmap.getWidth() / 2 < bitmap.getHeight() / 2 ? bitmap
.getWidth() : bitmap.getHeight();
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, rect, rect, paint);
return outBitmap;
}
以上这些代码才可以使得一个图形化控件成为一个圆形

一切只是为了充实自己!!stay hungry and stay foolish!!
原文地址:https://www.cnblogs.com/Catherine-Brain/p/3543768.html