編輯:關於 Android 程式設計
在製作頭像等場景時,我們常需要把圖片裁剪成圓形顯示。本文分享一個實用的做法:透過傳入圖片的高與寬來決定裁剪區域,最後用 Canvas 與 PorterDuff 模式把方圖變圓圖,並附上完整可運行的程式碼。
核心在於先判斷寬高的關係,取出一個正方形區域:當 width <= height 時,裁高度,取寬度不變、從頂部到 width 長度的區域;當 width > height 時,裁寬度,取高度不變、寬度居中。不同業務對裁剪區域要求不同,可依需求調整。接著用圓角矩形搭配 PorterDuffXfermode 的 SRC_IN 模式,把方圖「套」進圓形遮罩中。
參考程式碼 如下:
/**
* 轉換圖片成圓形
* @param bitmap 傳入 Bitmap 對象
* @return
*/
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;
}
整個流程可以拆成兩步:先用 drawRoundRect 畫出一個圓角(此處圓角半徑等於邊長一半,也就是正圓),再用 PorterDuffXfermode 的 SRC_IN 模式把原圖「填」進這個圓形範圍內。掌握這套 Canvas 合成技巧後,你就能輕鬆做出各種形狀的頭像裁剪效果。
用 ThumbnailUtils 提取視頻縮略圖
視頻播放器的列表裡總有成排的預覽圖,這些都是縮略圖。Android 提供 ThumbnailUtils 類來做這件事。 先看效果: MainActivity 的實
Android 滾輪時間選擇器:可擴充的日期與時間 Dialog
系統內建的日期選擇器未必符合所有產品需求,因此可嘗試以 WheelView 打造滾輪式時間選擇器。這類控制項可自訂標題、顯示欄位與是否開啟長期選項,適合日期、時間與證件有
應用耗電分析與優化:Battery Historian 實戰指南
在 Android 專案裡,電量消耗一直是最難量化、卻又最被用戶敏感的指標。使用者未必說得出你的產品有多少功能,但只要手機待機掉得比別人快,卸載的決定往往下得毫不留情。指
小米推送接入實戰:從 Demo 解析到移植上線的完整路線圖
前陣子忙著找工作,積累了不少收穫,卻一直沒空整理筆記。最近終於騰出手來,把小米推送的學習心得寫成這篇文章,希望能給需要接入 Android 消息推送的朋友一點參考。 為