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

Android 自定義 View(四):一步步還原 QQ 健康介面

編輯:關於 Android 程式設計

自定義 View 是 Android 的必備技能。這次我們拿 QQ 健康(運動)頁當作練習題,它涵蓋了自訂屬性、onMeasure、Path 繪製、DashPathEffect 與屬性動畫,可以說是一題綜合測驗。

最終效果可以自訂:標題顏色、線條顏色、運動步數、排名、好友平均步數;虛線下方的藍色指示條長度會隨平均步數變化而伸縮。

步驟一:定義自訂屬性

先在 res/values/attrs.xml 中宣告:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyQQHealthView">
        <attr name="titleColor" format="color" />
        <attr name="lineColor" format="color" />
    </declare-styleable>
</resources>

然後在佈局檔中先宣告命名空間,再使用這些屬性:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:myqq="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.tangyangkai.myview.MyQQHealthView
        android:id="@+id/myQQView"
        android:layout_width="match_parent"
        android:layout_height="530dp"
        android:layout_margin="15dp"
        myqq:lineColor="@color/font_tips"
        myqq:titleColor="@color/textcolor" />

</RelativeLayout>

步驟二:讀取自訂屬性

自定義 View 通常有三個建構子,且彼此逐層呼叫,屬性獲取只需寫在最內層那個:

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

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

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

    TypedArray array = context.getTheme()
            .obtainStyledAttributes(attrs, R.styleable.MyQQHealthView, defStyleAttr, 0);
    int n = array.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = array.getIndex(i);
        switch (attr) {
            case R.styleable.MyQQHealthView_titleColor:
                textColor = array.getColor(attr, Color.BLACK);
                break;
            case R.styleable.MyQQHealthView_lineColor:
                lineColor = array.getColor(attr, Color.BLACK);
                break;
        }
    }
    array.recycle();
    init();
}

四個要點:

  1. 用 obtainStyledAttributes() 取得樣式屬性陣列;
  2. 遍歷每個索引,取出對應屬性值;
  3. 用完記得呼叫 array.recycle() 回收資源;
  4. 必要的初始化放在這裡,不要在 onDraw 中 new 物件。onDraw 是高頻呼叫的方法,在其中大量配置記憶體會造成明顯的效能與 GC 壓力。

步驟三:重寫 onMeasure

不重寫 onMeasure 時,系統會採用預設實作:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

它的作用是測量控制項尺寸。Android 載入佈局時,會先測量各子 View 並回報所需空間,父 View 再依自身大小決定分配多少。核心是 MeasureSpec 的三種模式:

  • EXACTLY:父 View 指定子 View 必須是該尺寸,對應明確數值或 match_parent;
  • AT_MOST:子 View 最大隻能到該尺寸,對應 wrap_content;
  • UNSPECIFIED:父 View 不施加限制,子 View 想要多大就多大,實務上很少用到。

要讓 wrap_content 真正生效,就得自己處理:

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

    int width;
    int height;

    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;          // 佈局寫了固定值或 match_parent
    } else {
        width = widthSize * 1 / 2;  // wrap_content 時自訂
    }

    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else {
        height = heightSize * 3 / 4;
    }

    widthBg = width;
    heightBg = height;
    setMeasuredDimension(width, height);
    startAnim();
}

這裡為了避免畫面過小,wrap_content 時取寬的一半、高的四分之三,實際比例可依設計稿調整。

步驟四:onDraw 分層繪製

介面比較複雜,建議先在紙上畫出草圖、標好座標比例,再按「從上到下、從外到內」的順序實作。

(1)最底層背景:左上、右上帶圓角,左下、右下為直角。

// 繪製最底層背景
radiusBg = widthBg / 20;
pathBg.moveTo(0, heightBg);
pathBg.lineTo(0, radiusBg);
pathBg.quadTo(0, 0, radiusBg, 0);
pathBg.lineTo(widthBg - radiusBg, 0);
pathBg.quadTo(widthBg, 0, widthBg, radiusBg);
pathBg.lineTo(widthBg, heightBg);
pathBg.lineTo(0, heightBg);

backgroundPaint.setColor(Color.WHITE);
canvas.drawPath(pathBg, backgroundPaint);

canvas.drawRoundRect 只能四角全部圓或全部直角,做不出這種混合效果;用 lineTo(一階)搭配 quadTo(二階)就能精準控制每個轉角。

  • moveTo(x, y):不繪製,只移動畫筆、確定起點;
  • lineTo(x, y):一階貝塞爾曲線,畫直線;
  • quadTo(x1, y1, x2, y2):二階貝塞爾曲線,(x1,y1) 為控制點,(x2,y2) 為終點。

(2)圓弧進度

arcPaint.setStrokeWidth(widthBg / 20);
arcPaint.setStyle(Paint.Style.STROKE);   // 空心
arcPaint.setDither(true);                // 防色帶
arcPaint.setStrokeJoin(Paint.Join.ROUND);
arcPaint.setStrokeCap(Paint.Cap.ROUND);
arcPaint.setColor(lineColor);

// 圓弧範圍 = 圓的外接矩形
arcRect = new RectF(widthBg * 1 / 4, widthBg * 1 / 4,
                    widthBg * 3 / 4, widthBg * 3 / 4);

canvas.drawArc(arcRect, 120, 300, false, arcPaint);      // 背景大弧
arcPaint.setColor(textColor);
canvas.drawArc(arcRect, 120, arcNum, false, arcPaint);   // 進度小弧

drawArc 的五個參數依序是:外接矩形、起始角度、掃過角度、是否包含圓心(畫扇形時才用 true)、畫筆。

(3)文字

textPaint.setColor(textColor);
textPaint.setTextSize(widthBg / 10);
canvas.drawText(String.valueOf(walkNum), widthBg * 3 / 8, widthBg * 1 / 2 + 20, textPaint);

textPaint.setTextSize(widthBg / 15);
canvas.drawText(String.valueOf(rankNum), widthBg * 1 / 2 - 15, widthBg * 3 / 4 + 10, textPaint);

textPaint.setColor(lineColor);
textPaint.setTextSize(widthBg / 25);
canvas.drawText("截止13:45已走", widthBg * 3 / 8 - 10, widthBg * 5 / 12 - 10, textPaint);
canvas.drawText("好友平均2781步", widthBg * 3 / 8 - 10, widthBg * 2 / 3 - 20, textPaint);
canvas.drawText("第", widthBg * 1 / 2 - 50, widthBg * 3 / 4 + 10, textPaint);
canvas.drawText("名", widthBg * 1 / 2 + 30, widthBg * 3 / 4 + 10, textPaint);

canvas.drawText("最近7天", widthBg * 1 / 15, widthBg, textPaint);
myaverageTxt = String.valueOf(averageSize);
canvas.drawText("平均", widthBg * 10 / 15 - 15, widthBg, textPaint);
canvas.drawText(myaverageTxt, widthBg * 11 / 15, widthBg, textPaint);
canvas.drawText("步/天", widthBg * 12 / 15 + 20, widthBg, textPaint);

文字繪製本身不難,麻煩的是座標要逐一算準,建議用比例表示並搭配微調偏移量。

(4)虛線與每日柱狀線

linePaint.setStyle(Paint.Style.STROKE);
linePaint.setStrokeWidth(2);
linePaint.setColor(lineColor);
linePath.moveTo(widthBg * 1 / 15, widthBg + 80);
linePath.lineTo(widthBg * 14 / 15, widthBg + 80);
linePaint.setPathEffect(effects);
canvas.drawPath(linePath, linePaint);

rectSize = widthBg / 12;
rectAgHeight = widthBg / 10;

for (int i = 0; i < FourActivity.sizes.size(); i++) {
    rectPaint.setStrokeWidth(widthBg / 25);
    rectPaint.setStyle(Paint.Style.STROKE);
    rectPaint.setStrokeJoin(Paint.Join.ROUND);
    rectPaint.setStrokeCap(Paint.Cap.ROUND);

    float startHeight = widthBg + 90 + rectAgHeight;
    rectPath.moveTo(rectSize, startHeight);

    double percentage = Double.valueOf(FourActivity.sizes.get(i)) / Double.valueOf(averageSize);
    double height = percentage * rectAgHeight;
    rectPath.lineTo(rectSize, (float) (startHeight - height));

    rectPaint.setColor(textColor);
    canvas.drawPath(rectPath, rectPaint);

    textPaint.setColor(lineColor);
    canvas.drawText("0" + (i + 1) + "日", rectSize - 25, startHeight + 50, textPaint);

    rectSize += widthBg / 7;
}

DashPathEffect 的作用是把線段虛線化,建構子為 DashPathEffect(float[] intervals, float offset)。間隔陣列長度必須不小於 2,float[0] 與 float[1] 分別代表第一段實線與第一段虛線的長度,若後續還有偶數個值則繼續交替,若是奇數則重複第一個值循環;offset 為繪製偏移量。

DashPathEffect effects = new DashPathEffect(new float[]{5, 5}, 1);

把它設給 linePaint.setPathEffect() 即可。柱狀線的高度則是按當日步數佔平均步數的比例算出來的,所以改動平均步數後,線條長度會一起變化。

(5)底部水波紋

weavPaint.setColor(textColor);
weavPath.moveTo(0, heightBg);
weavPath.lineTo(0, heightBg * 10 / 12);
weavPath.cubicTo(widthBg * 1 / 10, heightBg * 10 / 12,
                 widthBg * 3 / 10, heightBg * 11 / 12,
                 widthBg, heightBg * 10 / 12);
weavPath.lineTo(widthBg, heightBg);
weavPath.lineTo(0, heightBg);
canvas.drawPath(weavPath, weavPaint);

weavPaint.setColor(Color.WHITE);
weavPaint.setTextSize(widthBg / 20);
canvas.drawText("成績不錯,繼續努力喲!", widthBg * 1 / 10 - 20, heightBg * 11 / 12 + 50, weavPaint);

cubicTo(x1, y1, x2, y2, x3, y3) 是三階貝塞爾曲線,兩個控制點加一個終點,用來畫較複雜的弧線。

步驟五:屬性動畫驅動

private void startAnim() {
    // 步數動畫
    ValueAnimator walkAnimator = ValueAnimator.ofInt(0, mySize);
    walkAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            walkNum = (int) animation.getAnimatedValue();
            postInvalidate();
        }
    });

    // 排名動畫
    ValueAnimator rankAnimator = ValueAnimator.ofInt(0, rank);
    rankAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            rankNum = (int) animation.getAnimatedValue();
            postInvalidate();
        }
    });

    // 圓弧動畫:超過平均值時以平均值為上限
    double size = mySize;
    double avgSize = averageSize;
    if (size > avgSize) {
        size = avgSize;
    }
    ValueAnimator arcAnimator = ValueAnimator.ofFloat(0, (float) (size / avgSize * 300));
    arcAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            arcNum = (float) animation.getAnimatedValue();
            postInvalidate();
        }
    });

    animSet.setDuration(3000);
    animSet.playTogether(walkAnimator, rankAnimator, arcAnimator);
    animSet.start();
}

屬性動畫的優勢在於它不局限于 View,也能作用於任意物件。設定好起始值與結束值、掛上監聽器,就能在 onAnimationUpdate 中拿到變化中的數值,再呼叫 postInvalidate() 觸發重繪。最後用 AnimatorSet 讓三組動畫同步播放。

這裡有個實作上很容易卡住的地方:一開始我把 startAnim() 寫在 init() 裡,動畫始終沒有反應。原因是自定義 View 初始化的階段,步數、排名、平均步數這些外部資料還沒傳進來,動畫自然算不出結果。後來改到 onMeasure() 末尾呼叫才正常。

步驟六:對外提供設定入口並在 Activity 中使用

public void reSet(int mysize, int myrank, int myaverageSize) {
    walkNum = 0;
    arcNum = 0;
    rankNum = 0;
    mySize = mysize;
    rank = myrank;
    averageSize = myaverageSize;
    startAnim();
}
public class FourActivity extends AppCompatActivity {

    private MyQQHealthView view;
    public static List<Integer> sizes = new ArrayList<>();
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);
        initView();
    }

    private void initView() {
        view = (MyQQHealthView) findViewById(R.id.myQQView);
        view.setMySize(2345);
        view.setRank(11);
        view.setAverageSize(5436);

        sizes.add(1234);
        sizes.add(2234);
        sizes.add(4234);
        sizes.add(6234);
        sizes.add(3834);
        sizes.add(7234);
        sizes.add(5436);

        btn = (Button) findViewById(R.id.set_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view.reSet(6534, 8, 4567);
            }
        });
    }
}

小結

整套流程走完,你會發現自定義 View 沒有想像中門檻高。真正的關鍵是兩件事:先把要畫的東西在紙上拆解成座標與比例,再嚴格遵守「初始化只 new 一次、繪製方法裡不配置記憶體」的原則。熟練之後,再複雜的介面也只是把圖形拆成幾段 Path 而已。

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