編輯:Android 開發實例
之前在論壇上找過不少把圖片裁成圓形的方法,效果都不太理想。後來因為業務需求要將頭像以圓形顯示,才自己動手做了一版,這裡記錄做法與思路。
核心邏輯是依傳入圖片的高(height)與寬(width)決定要裁哪個方向,目標是先取出一個正方形區域,再把它裁成圓形:
若 width <= height,裁高度。寬度保持不變,高度從頂部取到與寬度相同的長度。
若 width > height,裁寬度。高度保持不變,寬度取圖片中央的區域。
不同業務對裁剪區域的要求可能不同(例如想取頂部而非中央),只要調整 src 矩形即可。
/**
* 轉換圖片成圓形
* @param bitmap 傳入的 Bitmap 物件
* @return 圓形 Bitmap
*/
public Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / 2;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
final RectF rectF = new RectF(dst);
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, src, dst, paint);
return output;
}
整個技巧可以分成三個動作。
第一步,在目的地畫布上畫一個圓角矩形,圓角半徑設為邊長的一半(roundPx),這樣四個圓角接起來剛好就是一個正圓。此時畫布上是「實心圓、其餘透明」。
第二步,設定 PorterDuffXfermode(Mode.SRC_IN)。這個混合模式的意思是:只保留來源圖(剛畫的圓)與目標圖重疊的部分,且以「已在畫布上的內容」為遮罩。因此後續畫上去的圖片,會被裁切成圓形。
第三步,用 drawBitmap(bitmap, src, dst, paint) 把原圖從 src 區域映射到 dst 區域畫上去,超出圓的部分就被丟掉了。
paint.setAntiAlias(true) 不能省,否則圓形邊緣會出現鋸齒。另外要留意順序:先畫遮罩形狀、再設 Xfermode、最後畫圖,顛倒就不會有效果。
這個方法每次都會建立新的 Bitmap,在 ListView 中大量使用時容易撐高記憶體。若效能吃緊,可以考慮改用 BitmapShader 搭配 Canvas.drawCircle(),不必複製位圖就能達到同樣效果。
另一個常見做法是直接寫一個繼承 ImageView 的自訂控制項,在 onDraw() 中用 clipPath 或 shader 裁切,這樣能避免反覆配置 Bitmap,也比較容易與 Glide、Picasso 這類載入框架搭配。
Android JSON 解析入門
JSON 是一種輕量級的資料交換格式,常用於應用程式與伺服器之間傳輸資料。相比 XML,JSON 結構更簡潔,也更容易在 Android 中解析。本文說明 JSON 的基
Android時間與日期元件用法實例:TimePicker 與 DatePicker
繼上一篇關於時間與日期設定的示例之後,本文接著介紹 Android 介面元件中與時間、日期相關的設定元件,希望能對大家有所幫助。具體如下: 時間日期設定元件:TimePi
Android 表單字段驗證的實例代碼詳解
在登錄、註冊這類表單場景中,字段驗證是必不可少的一環——用戶名不能為空、郵箱格式要正確、手機號要合法等。借助開源的 Android-Validator 庫,我們能優雅地完
Android Fragment 多級跳轉與逐級返回的完整實現方案
Fragment 的返回鍵管理是個經典難題:頁面一層層往下跳,按返回要一級級退回去,中間某一層可能還想攔截返回事件做別的事(比如先關菜單而不是退出)。本文給出一套接口 +