Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 ImageView:點擊圖片不同區域觸發不同事件並做好螢幕適配

編輯:關於 Android 程式設計

需求很常見:拿到一張背景圖,客戶要求點擊圖片的不同區域跳到不同頁面或執行不同操作。

直覺的做法是在布局裡鋪一層透明的 Button 或 TextView,把每個可點區域擺上去。但這樣做有個致命問題——不同解析度的螢幕上圖片被縮放的比例不同,硬編碼的位置很快就會錯位,適配成本極高。

本文採用另一條路徑:以圖片的原始像素座標描述可點區域,運行時再換算成實際顯示座標,從根本上解決適配問題。

一、確定點擊區域的座標

上圖中需要響應點擊的區域是圓形,因此只需要圓心座標與半徑三個值。用 Mark Man 這類標尺工具就能量出來。

由於量到的是 px,而運行時需要 dp,這裡採用簡化的換算方式(dp = px / 2,對應 mdpi 基準螢幕),並在程式碼中統一透過 density 縮放。

座標配置寫在 arrays.xml 中,分成兩組:string-array 保存區域的識別碼與顯示名稱,integer-array 保存「圓心 x、圓心 y、半徑」三個整數。

<!-- 區域清單,順序即為繪製與判定順序 -->
<string-array name="man_head">
    <item>man_hair</item>
    <item>man_eye</item>
    <item>man_mouth</item>
    <item>man_throat</item>
    <item>man_mind</item>
    <item>man_ear</item>
    <item>man_nose</item>
</string-array>

<!-- 每個區域對應一組「代碼 + 名稱」 -->
<string-array name="man_hair_code">
    <item>hair</item><item>頭發</item>
</string-array>
<string-array name="man_eye_code">
    <item>eye</item><item>眼</item>
</string-array>
<string-array name="man_mouth_code">
    <item>mouth</item><item>口腔</item>
</string-array>
<string-array name="man_throat_code">
    <item>throat</item><item>咽喉</item>
</string-array>
<string-array name="man_mind_code">
    <item>mind</item><item>頭/腦</item>
</string-array>
<string-array name="man_ear_code">
    <item>ear</item><item>耳朵</item>
</string-array>
<string-array name="man_nose_code">
    <item>nose</item><item>鼻</item>
</string-array>

<!-- 每組三個值:圓心 x、圓心 y、半徑 -->
<integer-array name="man_hair"><item>30</item><item>46</item><item>20</item></integer-array>
<integer-array name="man_eye"><item>30</item><item>103</item><item>20</item></integer-array>
<integer-array name="man_mouth"><item>30</item><item>160</item><item>20</item></integer-array>
<integer-array name="man_throat"><item>30</item><item>220</item><item>20</item></integer-array>
<integer-array name="man_mind"><item>289</item><item>44</item><item>20</item></integer-array>
<integer-array name="man_ear"><item>289</item><item>105</item><item>20</item></integer-array>
<integer-array name="man_nose"><item>289</item><item>162</item><item>20</item></integer-array>

這種「清單 + 編碼表 + 座標表」的三段式結構有個好處:新增區域時只改 XML,不用動 Java 邏輯。

二、自定義 ImageView 控件

BaseBodyView 封裝了通用邏輯:讀取座標、建立 Path、攔截觸摸事件、判定命中區域、回撥結果。

/**
 * 身體區域點擊基類
 * 每個區域以「圓心 x, y + 半徑 r」三個值描述
 */
public abstract class BaseBodyView extends ImageView {

    protected Context mContext;

    /** 所有可點擊區域 */
    private Map<String, BodyArea> mBodyArea;
    /** 本次命中的區域 */
    private Set<String> mFocus;

    protected Paint paint = new Paint();
    protected RectF mPathRectF = new RectF();
    protected OnBodyClickListener mBodyClick;

    public BaseBodyView(Context context) {
        this(context, null);
    }

    public BaseBodyView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BaseBodyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initDatas();
    }

    private void initDatas() {
        mBodyArea = new HashMap<>();
        mFocus = new HashSet<>();
        initBodyArea();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 除錯時可打開以下註解,把命中區域畫出來確認座標是否正確
        // for (String key : mFocus) {
        //     canvas.drawPath(mBodyArea.get(key).getPath(), paint);
        // }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mBodyClick != null) {
            checkAreas(event);
            if (!mFocus.isEmpty()) {
                for (String key : mFocus) {
                    BodyArea area = mBodyArea.get(key);
                    mBodyClick.onBodyClick(0, area.getPtKeys());
                }
            }
        }
        return super.onTouchEvent(event);
    }

    /** 遍歷所有區域,找出包含觸摸點的那一個 */
    private void checkAreas(MotionEvent event) {
        mFocus.clear();
        for (String key : mBodyArea.keySet()) {
            mPathRectF.setEmpty();
            Path path = mBodyArea.get(key).getPath();
            path.computeBounds(mPathRectF, true);
            if (mPathRectF.contains(event.getX(), event.getY())) {
                mFocus.add(key);
                break;
            }
        }
    }

    /** 從資源中讀取配置,組裝成 Path */
    public void initBodyArea() {
        mBodyArea.clear();
        mFocus.clear();

        String[] keys = mContext.getResources().getStringArray(initArray());
        if (keys == null) return;

        for (String key : keys) {
            int idenId = mContext.getResources()
                    .getIdentifier(key, "array", initPackage());
            int[] paths = mContext.getResources().getIntArray(idenId);

            idenId = mContext.getResources()
                    .getIdentifier(key + "_code", "array", initPackage());
            String[] ptKeys = mContext.getResources().getStringArray(idenId);

            mBodyArea.put(key, new BodyArea(ptKeys, paths));
        }
    }

    /** px 轉 dp,實現不同解析度手機的兼容 */
    private float toDip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return pxValue * scale + 0.5f;
    }

    /** 子類提供區域清單的資源 id */
    protected abstract int initArray();

    /** 子類提供資源所在的 package 名 */
    protected abstract String initPackage();

    public void setOnBodyClickListener(OnBodyClickListener listener) {
        this.mBodyClick = listener;
    }

    public interface OnBodyClickListener {
        void onBodyClick(int position, String[] keys);
    }

    /** 圓形區域 */
    class BodyArea {
        private String[] mPtKeys;
        private Path mPath;

        public BodyArea(String[] ptKeys, int[] paths) {
            mPtKeys = ptKeys;
            mPath = new Path();
            if (paths.length >= 3) {
                mPath.addCircle(
                        toDip(mContext, paths[0]),
                        toDip(mContext, paths[1]),
                        toDip(mContext, paths[2]),
                        Path.Direction.CW);
            }
            mPath.close();
        }

        public String[] getPtKeys() { return mPtKeys; }
        public Path getPath() { return mPath; }
    }
}

子類非常輕量,只需回報兩項配置。注意類名要與 string-array 的命名規則對應:

public class ManHeadView extends BaseBodyView {

    public ManHeadView(Context context) {
        this(context, null);
    }

    public ManHeadView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ManHeadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected int initArray() {
        return R.array.man_head;
    }

    @Override
    protected String initPackage() {
        return mContext.getPackageName();
    }
}

三、布局配置

這裡有個關鍵屬性:必須設定 android:scaleType="matrix"。只有 matrix 模式下,ImageView 才會以圖片自身的座標系統進行繪製與命中判斷,前面算好的座標才對得上。用 fitXY 或 centerCrop 會導致座標錯位。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <com.app.gaobaiq.widget.customview.ManHeadView
        android:id="@+id/img_head"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:scaleType="matrix"
        android:src="@drawable/view_man_head" />

</LinearLayout>

四、使用方式

接入時只需註冊監聽,回撥中直接拿到該區域的代碼與名稱:

mImgHead.setOnBodyClickListener(new ManHeadView.OnBodyClickListener() {
    @Override
    public void onBodyClick(int position, String[] keys) {
        String message = "Code:" + keys[0] + ", Name:" + keys[1];
        ToastUtils.ToastMessage(getActivity(), message);
    }
});

五、方案取捨與擴展空間

這個方案的核心思路是「用比例座標描述,用密度換算適配」,換任何一張圖只要重算座標表即可,邏輯層完全不用動。

幾個可以進一步打磨的地方:

  • 形狀擴展:目前只支援圓形。若要支援多邊形,把 BodyArea 中的 addCircle 換成 addPath 並改用 path.contains(x, y) 判定即可,配置格式改為四組座標一組;
  • 非等比縮放:如果圖片被拉伸變形,需要在 onSizeChanged 中記錄實際縮放比例,對座標做二次換算;
  • 多點命中:目前找到第一個符合區域就 break。若區域有重疊且需要全部回調,去掉 break 即可;
  • 無障礙:圖片上的點擊區域對 TalkBack 使用者是不可見的,正式專案建議同時提供等價的列表或選單入口。

除錯期間強烈建議打開 onDraw 中的註解,把 Path 實際畫出來核對一遍——座標量錯幾個像素是常事,眼睛看一下比反覆猜要快得多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved