編輯:Android 技術基礎
上一節我們認識了 Xfermode 家族裡最實用的那位「三兒子」——PorterDuffXfermode,它的建構子只收一個參數:PorterDuff.Mode。我們先看過官方文件裡的 16 種混排效果,接著又自己寫程式把文件提到的 18 種逐一驗證了一遍,多出來的兩種正是 ADD 與 OVERLAY。
不過光「看過、驗證過」還不夠,真正能把知識留下來的方式是拿來做點東西。所以本節我們安排一個實作題:用自訂 ImageView 做出圓形與圓角圖片。
還記得在 2.3.4 節聊 ImageView 的時候,我們示範過最樸素的圓形圖片做法——在 Bitmap 上呼叫 clipPath 硬切出一個圓。這次換一條路:改用 PorterDuff.Mode.DST_IN 來完成。廢話不多說,開始今天的內容。
PS:本節範例靈感取自弘洋的「Android Xfermode 實戰:實現圓形、圓角圖片」。另外也把 PorterDuff.Mode 的效果圖再貼一次,方便對照:
執行後的效果如下:

目標很明確:一顆正圓,一張圓角矩形,靠的都是 PorterDuff.Mode.DST_IN。先把流程拆開來看,寫程式的時候就不容易迷路。
- Step 1:想清楚 Xfermode 的兩層結構。Xfermode 說穿了就是兩張圖的疊合問題:先畫上去的叫 DST(目標圖),後畫上去的叫 SRC(來源圖)。我們要圓形或圓角,做法是先把要顯示的圖片畫成 DST(這裡直接用 ImageView 的 src 屬性塞進去),再把圓形或圓角矩形畫成 SRC。最終想保留的是兩者「相交且屬於圖片」的那塊區域,所以模式選 DST_IN。
- Step 2:把可調參數抽出來。既然 View 要同時支援圓形與圓角,就得有個屬性來切換型別;圓角還需要一個半徑值。做法是在 attrs.xml 宣告自訂屬性,再在自訂 View 的建構子裡用 TypedArray 取出來。
- Step 3:把尺寸算對。如果是圓形,寬高必須相等,因此以最小值為準——在 onMeasure() 裡用 getMeasuredWidth()/getMeasuredHeight() 比大小,再 setMeasuredDimension(x, x)。接著在 onDraw() 取得圖片本身的寬高,與 View 的寬高算出縮放比例;為了鋪滿且不留白,這裡取大值,確保運算後的圖片尺寸一定大於等於 View 尺寸。
- Step 4:開始繪製。寫一個負責畫形狀的方法,初始化畫筆後把 setXfermode 設為 PorterDuff.Mode.DST_IN,先畫圖片、再畫遮罩形狀,交錯的部分自然就留下來了。
- Step 5:處理快取。用 WeakReference 快取合成後的 Bitmap,避免每次 onDraw 都重新配置記憶體與重繪;在 invalidate 時清掉快取即可。
流程清楚了,再看程式碼就是順水推舟的事。
先宣告自訂屬性:res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CircleImageView"> <attr name="Radius" format="dimension"/> <attr name="type"> <enum name="circle" value="0"/> <enum name="round" value="1"/> </attr> </declare-styleable> </resources>
接著是主角:CircleImageView.java
/**
* 自訂 ImageView:以 PorterDuff.Mode.DST_IN 實作圓形/圓角圖片
*/
public class CircleImageView extends ImageView {
private Paint mPaint;
private Xfermode mXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
private Bitmap mMaskBitmap; // 遮罩形狀
private WeakReference<Bitmap> mWeakBitmap; // 合成結果快取
// 圖片相關屬性
private int type; // 型別:圓形或圓角
public static final int TYPE_CIRCLE = 0;
public static final int TYPE_ROUND = 1;
private static final int BODER_RADIUS_DEFAULT = 10; // 圓角預設值
private int mBorderRadius; // 圓角大小
public CircleImageView(Context context) {
this(context, null);
}
public CircleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
// 取出自訂屬性
TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView);
mBorderRadius = tArray.getDimensionPixelSize(R.styleable.CircleImageView_Radius, BODER_RADIUS_DEFAULT);
type = tArray.getInt(R.styleable.CircleImageView_type, TYPE_CIRCLE);
tArray.recycle();
}
public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (type == TYPE_CIRCLE) {
// 圓形必須等寬等高,取短邊為準
int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
setMeasuredDimension(width, width);
}
}
@Override
protected void onDraw(Canvas canvas) {
// 先看看快取裡有沒有現成的結果
Bitmap bitmap = mWeakBitmap == null ? null : mWeakBitmap.get();
if (bitmap == null || bitmap.isRecycled()) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas drawCanvas = new Canvas(bitmap);
// 計算縮放比例:取大值可鋪滿整個 View,不留黑邊
float scale;
if (type == TYPE_ROUND) {
scale = Math.max(getWidth() * 1.0f / width, getHeight() * 1.0f / height);
} else {
scale = getWidth() * 1.0f / Math.min(width, height);
}
drawable.setBounds(0, 0, (int) (scale * width), (int) (scale * height));
drawable.draw(drawCanvas);
// 取得遮罩形狀
if (mMaskBitmap == null || mMaskBitmap.isRecycled()) {
mMaskBitmap = getBitmap();
}
mPaint.reset();
mPaint.setFilterBitmap(false);
mPaint.setXfermode(mXfermode);
// 先圖片後形狀,交集處即為最終顯示範圍
drawCanvas.drawBitmap(mMaskBitmap, 0, 0, mPaint);
mPaint.setXfermode(null);
// 快取起來,避免每次 onDraw 重新配置記憶體
mWeakBitmap = new WeakReference<Bitmap>(bitmap);
}
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mPaint);
}
@Override
public void invalidate() {
// 清除快取,強制下次重繪時重新合成
if (mWeakBitmap != null) {
mWeakBitmap.clear();
mWeakBitmap = null;
}
if (mMaskBitmap != null && !mMaskBitmap.isRecycled()) {
mMaskBitmap.recycle();
mMaskBitmap = null;
}
super.invalidate();
}
// 畫出遮罩形狀:圓形或圓角矩形
private Bitmap getBitmap() {
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
if (type == TYPE_ROUND) {
canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), mBorderRadius, mBorderRadius, paint);
} else {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint);
}
return bitmap;
}
}
最後在版面配置裡掛上去:activity_main.xml
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.jay.xfermodedemo1.CircleImageView android:layout_width="160dp" android:layout_height="240dp" android:layout_margin="10dp" android:src="@mipmap/ic_bg_meizi2" app:type="circle" /> <com.jay.xfermodedemo1.CircleImageView android:layout_width="160dp" android:layout_height="280dp" android:layout_margin="10dp" android:src="@mipmap/ic_bg_meizi1" app:Radius="30dp" app:type="round" /> </LinearLayout>
第一次讀會卡住的地方,多半是縮放比例那幾行;把它想成「要鋪滿容器該放大幾倍」就通了。剩下的都是例行公事。
XfermodeDemo1.zip
本節我們完成了 Xfermode 與 PorterDuff 的第一個實作案例:設定 DST_IN 模式,做出圓形與圓角 ImageView。到這裡,你對 PorterDuff.Mode 的用法應該已經有點概念了——它本質上就是「兩張圖怎麼合」的問題,剩下的只是把順序與模式選對。
打铁趁熱,下一節我們再安排一個例子練手。就聊到這裡,謝謝。
Android LinearLayout 線性布局:weight 權重、分割線與常見陷阱
LinearLayout 的核心概念LinearLayout 會將子元件排列成一條線,可設定水平或垂直。它最實用的特性是 weight 權重,常用於畫面比例分配與螢幕適配
ContentProvider 入門:讀取系統資料與自訂內容提供者
ContentProvider 的作用ContentProvider 是 Android 四大元件之一,主要用於在不同應用程式之間安全地共用資料。它可以用來讀取聯絡人、簡
打造一個到處都能複用的萬能 BaseAdapter
為什麼要自己造一個「萬能」適配器? 只要碰過 ListView、GridView 這類需要適配器的控件,幾乎每寫一個列表就要重寫一個 BaseAdapter,同一套邏輯反
Android 教學:用 ImageButton 換掉預設的方角按鈕
Android 預設的 Button 就算調了樣式做出圓角,觀感上常常還是差一點。想要真正把按鈕做得好看,ImageButton 是更直接的選擇——直接把設計好的圖當按鈕