一般要做正圓形圖片,只能是正方形的基礎上才能實現,否則就變成橢圓了,下面說說如何使長方形的圖片生成正圓形圖片
廢話不多說,沒圖沒真相,先上圖吧:
原圖:

變成正圓后:

下面上代碼:
public static Bitmap makeRoundCorner(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int left = 0, top = 0, right = width, bottom = height; float roundPx = height/2; if (width > height) { left = (width - height)/2; top = 0; right = left + height; bottom = height; } else if (height > width) { left = 0; top = (height - width)/2; right = width; bottom = top + width; roundPx = width/2; } ZLog.i(TAG, "ps:"+ left +", "+ top +", "+ right +", "+ bottom); Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); int color = 0xff424242; Paint paint = new Paint(); Rect rect = new Rect(left, top, right, bottom); RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; }
下面再解釋下:
由于圖片是長方形,所以圖片的 寬、高 肯定會有一邊要小于另一邊,要生成正方形就已最小的一邊為基準,再來裁切定位另一邊的顯示范圍
至于圓角的半徑則是正方形寬的一半,用過 CSS 的就知道,畫圓很方便 border-radius設為 50% 就可以了,都是一個道理
android 的 UI 真是太繁瑣了
矩形畫個圓角的代碼:
public static Bitmap makeRoundCorner(Bitmap bitmap, int px) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); int color = 0xff424242; Paint paint = new Paint(); Rect rect = new Rect(0, 0, width, height); RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, px, px, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } 新聞熱點
疑難解答