Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中使用Bitmap類將矩形圖片轉為圓形的方法

Android中使用Bitmap類將矩形圖片轉為圓形的方法

編輯:關於Android編程

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

2016319163739626.jpg (480×800)

變成正圓後:

2016319163810889.jpg (480×800)

下面上代碼:

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; 
} 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved