有时android应用程序中需要用到圆角的图片,但是不可能每次上传的时候都处理成圆角的,这时就需要程序进行自动处理。
下面的代码可以将直角的bitmap对象转换为圆角的图片对象
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,int radius,double wh) {\r\n//radius为圆角的大小(1-1000),wh为图片的长宽比,如正方形为1\r\n \r\nint w=bitmap.getWidth();\r\nint h=bitmap.getHeight();\r\n \r\n //将画布的四角圆化\r\n final int color = Color.RED; \r\n final Paint paint = new Paint();\r\n int nw=w;\r\n int nh=h;\r\n if(wh>0)\r\n {\r\n if(wh>w/h)\r\n {\r\n nw=w;\r\n nh=(int)(nw/wh);\r\n }\r\n else\r\n {\r\n nh=h;\r\n nw=(int)(nh*wh);\r\n }\r\n }\r\n Bitmap output = Bitmap.createBitmap(nw,nh, Bitmap.Config.ARGB_8888);\r\n //得到画布\r\n Canvas canvas = new Canvas(output); \r\n //得到与图像相同大小的区域 由构造的四个值决定区域的位置以及大小\r\n final Rect rect = new Rect((w-nw)/2, (h-nh)/2, nw, nh);\r\n final Rect rect2 = new Rect(0,0, nw, nh);\r\n final RectF rectF = new RectF(rect2); \r\n //值越大角度越明显\r\n final float roundPx = radius*bitmap.getWidth()/1000; \r\n paint.setAntiAlias(true); \r\n canvas.drawARGB(0, 0, 0, 0); \r\n paint.setColor(color); \r\n //drawRoundRect的第2,3个参数一样则画的是正圆的一角,如果数值不同则是椭圆的一角\r\n canvas.drawRoundRect(rectF, roundPx,roundPx, paint); \r\n \r\n paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); \r\n canvas.drawBitmap(bitmap, rect, rect2, paint); \r\n \r\n return output; \r\n }