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

手把手畫一個蜂窩 View:Android 自定義 View 實戰

編輯:關於 Android 開發

單看效果,這個蜂窩好像沒什麼實際用處——如果不加監聽回調,一張圖片就能替代。寫這篇的目的不是做一個能上線的組件,而是練思維:把一個「看起來很隨意」的圖形拆解成可用代碼表達的幾何關係,這個能力才是應對各種奇怪自定義 View 需求的底子。

本文的代碼是伴隨文章同步寫出來的,也就是說一邊想一邊敲。所以過程會顯得有些反覆——先寫死坐標,發現畫不對,再回頭改成參數化。這才是真實的開發節奏,技術本來就是一點點累起來的,不可能一步登天。

另外,這一系列文章是建立在前幾篇基礎知識之上的。如果你剛接觸自定義 View,建議先看看之前記錄學習過程的那幾篇。前面幾篇裡其實犯過一些錯誤,我沒有回去改掉,因為那些錯誤大家幾乎都會犯,而後面的文章會指出它們——把踩坑的經歷留下來,等成了高手回頭看當年的自己,也挺有意思。

效果圖:

第一步:先搞清六邊形的幾何關係

設正六邊形的邊長為 a。因為每個內角是 120°,可以推出它的高度為 √3·a。有了這兩個量,六個頂點的相對位置就完全確定了。

代碼實現:

float height = (float) (Math.sqrt(3) * mLength);
mPath.moveTo(mLength / 2, 0);
mPath.lineTo(0, height / 2);
mPath.lineTo(mLength / 2, height);
mPath.lineTo((float) (mLength * 1.5), height);
mPath.lineTo(2 * mLength, height / 2);
mPath.lineTo((float) (mLength * 1.5), 0);
mPath.lineTo(mLength / 2, 0);
mPath.close();

畫出來是這樣:

第二步:橫向排開——偏移量算錯了

直覺上,緊挨着的兩個六邊形之間偏移一個六邊形的寬就够了。寬是 a/2 + a + a/2 = 2a,於是先試 2a:

for (int i = 0; i < 3; i++) {
    int offset = mLength * 2 * i;
    mPath.moveTo(mLength / 2 + offset, 0);
    mPath.lineTo(0 + offset, height / 2);
    mPath.lineTo(mLength / 2 + offset, height);
    mPath.lineTo((float) (mLength * 1.5) + offset, height);
    mPath.lineTo(2 * mLength + offset, height / 2);
    mPath.lineTo((float) (mLength * 1.5) + offset, 0);
    mPath.lineTo(mLength / 2 + offset, 0);
    mPath.close();
}

不對。底下空出來的那個三角形塞不下第二行——蜂窩是錯縫排列的,如果第一行緊密相鄰,第二行的格子就沒有落腳的地方。

怎麼辦?把 offset 加大,多加一個邊長,讓相鄰六邊形之間留出正好一個错位量的縫隙。

這下橫向排布對了。

第三步:把坐標參數化

接下來要畫第二行,但發現之前的路徑坐標全是硬編碼的,沒法複用。得改成「給定左上角一個起點,就能畫出一個六邊形」。

改完後:

float height = (float) (Math.sqrt(3) * mLength);

for (int i = 0; i < 3; i++) {
    float offset = mLength * 3 * i;   // 橫坐標偏移量
    float x = mLength / 2 + offset;   // 左上角 x
    float y = 0;
    getPath(height, x, y);
}

效果的確和之前一樣,但方法已經變了——現在它是可複用的。

第四步:畫第二行

偶數行從 x = a/2 起,奇數行則要錯半個身位,起點落在 2a、height/2 處。

先把畫路徑的邏輯抽成獨立方法(Android Studio 快捷鍵 Ctrl + Alt + M):

// 根據左上角一點繪製整個正六邊形
private void getPath(float height, float x, float y) {
    mPath.moveTo(x, y);
    mPath.lineTo(x - mLength / 2, height / 2 + y);
    mPath.lineTo(x, height + y);
    mPath.lineTo(x + mLength, height + y);
    mPath.lineTo((float) (x + 1.5 * mLength), height / 2 + y);
    mPath.lineTo(x + mLength, y);
    mPath.lineTo(x, y);
    mPath.close();
}

然後循環畫第二行:

for (int i = 0; i < 2; i++) {
    float offset = mLength * 3 * i;
    float x = mLength * 2 + offset;
    float y = height / 2;
    getPath(height, x, y);
}
canvas.drawPath(mPath, mPaint);

第五步:控制行數與列數

把行數、列數提成成員變量:

private int mColumnsCount = 3;   // 每行的個數
private int mLineCount = 3;      // 行數

onDraw 外面再套一層大循環,用 j 的奇偶決定這一行怎麼畫:

@Override
protected void onDraw(Canvas canvas) {
    float height = (float) (Math.sqrt(3) * mLength);

    for (int j = 0; j < mLineCount; j++) {
        if (j % 2 == 0) {
            mPaint.setColor(Color.parseColor("#FFBB33"));
            for (int i = 0; i < mColumnsCount; i++) {
                float offset = mLength * 3 * i;
                float x = mLength / 2 + offset;
                float y = j * height / 2;
                getPath(height, x, y);
            }
            canvas.drawPath(mPath, mPaint);
            mPath.reset();
        } else {
            mPaint.setColor(Color.parseColor("#AA66CC"));
            for (int i = 0; i < mColumnsCount; i++) {
                float offset = mLength * 3 * i;
                float x = mLength * 2 + offset;
                float y = (height / 2) * j;
                getPath(height, x, y);
            }
            canvas.drawPath(mPath, mPaint);
            mPath.reset();
        }
    }
}

能畫出來了,但所有格子同色實在難看。那就讓顏色也變起來。

第六步:多色填充

用一個 List 存調色板:

private ArrayList<Integer> mColorList;

mColorList = new ArrayList<>();
mColorList.add(Color.parseColor("#33B5E5"));
mColorList.add(Color.parseColor("#AA66CC"));
mColorList.add(Color.parseColor("#99CC00"));
mColorList.add(Color.parseColor("#FFBB33"));
mColorList.add(Color.parseColor("#FF4444"));

循環裡按行取色:

for (int j = 0; j < mLineCount; j++) {
    mPaint.setColor(mColorList.get(j % mColorList.size()));
    ...
}

像點樣子了。接下來往中間填文字。

第七步:加文字

先給每個蜂窩編號。

按上面的循環,j 是行、i 是列,規律很直白:編號 = j × 3 + i(這裡的 3 就是每行個數,實戰中應該寫成 mColumnsCount)。

有了左上角坐標 x、y,中心點也就是 (x + a/2, y + height/2)。

開一個 List 存文字:

private ArrayList<String> mTextList;

mTextList = new ArrayList<>();
for (int i = 0; i < mLineCount * mColumnsCount; i++) {
    mTextList.add(String.valueOf(i + 1));
}

繪製文字時有個順序陷阱:必須先畫 path 再畫文字,反過來文字會被後畫的圖形蓋掉。

float txtLength = mTextPaint.measureText(mTextList.get(txtId));
canvas.drawText(mTextList.get(txtId),
        x + mLength / 2 - txtLength / 2,   // 水平居中
        y + height / 2 + 5,                // 垂直方向做點基線補償
        mTextPaint);

完整的 onDraw:

@Override
protected void onDraw(Canvas canvas) {
    float height = (float) (Math.sqrt(3) * mLength);

    for (int j = 0; j < mLineCount; j++) {
        mPaint.setColor(mColorList.get(j % mColorList.size()));

        for (int i = 0; i < mColumnsCount; i++) {
            int txtId = j * mColumnsCount + i;
            float offset = mLength * 3 * i;
            float x = (j % 2 == 0) ? (mLength / 2 + offset) : (mLength * 2 + offset);
            float y = j * height / 2;

            mPath.reset();
            getPath(height, x, y);
            canvas.drawPath(mPath, mPaint);

            float txtLength = mTextPaint.measureText(mTextList.get(txtId));
            canvas.drawText(mTextList.get(txtId),
                    x + mLength / 2 - txtLength / 2,
                    y + height / 2 + 5,
                    mTextPaint);
        }
    }
}

第八步:暴露自定義屬性

把行數、列數、文本、顏色都做成可外部設置的接口,別忘了每個 setter 末尾調 invalidate() 請求重繪:

public void setColumnsCount(int columnsCount) {
    this.mColumnsCount = columnsCount;
    invalidate();
}

public void setLineCount(int lineCount) {
    this.mLineCount = lineCount;
    invalidate();
}

public void setTextList(ArrayList<String> textList) {
    mTextList.clear();
    mTextList.addAll(textList);
    invalidate();
}

public void setColorList(ArrayList<Integer> colorList) {
    mColorList.clear();
    mColorList.addAll(colorList);
    invalidate();
}

第九步:別忘了 onMeasure

只寫 onDraw 的話,wrap_content 是沒有意義的。要讓它在佈局裡表現正常,得自己算尺寸:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);

    if (widthMode == MeasureSpec.AT_MOST) {
        // 每行 3a,錯行多出半個,這裡做個粗略估算
        widthSize = (int) ((3f * mColumnsCount + 0.5f) * mLength);
    }
    if (heightMode == MeasureSpec.AT_MOST) {
        heightSize = (int) ((mLineCount / 2f + 0.5f) * (Math.sqrt(3) * mLength));
    }
    setMeasuredDimension(widthSize, heightSize);
}

用 wrap_content 試一下:

尺寸對上了。這裡只處理了 AT_MOST,EXACTLY 的情況留給有興趣的人自己擴展——比如按「撐滿父容器」反推邊長。

還差一步:交互

到這裡,一個蜂窩 View 基本成型。但它還是「沒什麼用」,因為沒有交互——沒有交互的話,一張切圖完全可以勝任。

所以這次先留一個尾巴:事件處理。邏輯其實不複雜——判斷觸摸點是否落在某個 Path 內(mPath.contains(x, y) 不可用時可以配合 Region),在 ACTION_UP 時命中就按編號回調。這個問題留到下一篇再解決。

回顧整個過程,你會發現真正花時間的往往不是 Canvas API,而是「把一張圖翻譯成坐標公式」這一步。offset 該是 2a 還是 3a、中心點怎麼算、文字基線怎麼補償——這些想清楚了,代碼自然就下來了。

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