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

Android 自定義 View:仿 QQ 健康運動介面

編輯:關於 Android 程式設計

QQ 健康中的運動介面具有圓弧進度、步數排名、好友平均步數與底部波紋等元素。這類介面可以通過自定義 View 完成,既能展示數據,也能呈現豐富的視覺效果。

自定義 View 的基本流程

  1. 定義自定義屬性。
  2. 在構造方法中獲取屬性。
  3. 在 onMeasure 中計算 View 大小。
  4. 在 onDraw 中繪製界面內容。
  5. 使用屬性動畫實現數字與進度變化。

定義屬性

<resources>
    <attr name="titleColor" format="color" />
    <attr name="lineColor" format="color" />

    <declare-styleable name="MyQQHealthView">
        <attr name="titleColor" />
        <attr name="lineColor" />
    </declare-styleable>
</resources>

獲取屬性

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);
    if (attr == R.styleable.MyQQHealthView_titleColor) {
        textColor = array.getColor(attr, Color.BLACK);
    } else if (attr == R.styleable.MyQQHealthView_lineColor) {
        lineColor = array.getColor(attr, Color.BLACK);
    }
}
array.recycle();

繪製圓弧

圓弧部分可以使用 drawArc 完成。先確定圓弧所在的外接矩形,再設置起始角度與掃描角度。

arcPaint.setStrokeWidth(widthBg / 20);
arcPaint.setStyle(Paint.Style.STROKE);
arcPaint.setColor(lineColor);

RectF 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);

繪製文字與虛線

文字部分可以根據步數、排名與平均步數進行定位。虛線可以使用 DashPathEffect。

DashPathEffect effects = new DashPathEffect(new float[]{5, 5}, 1);
linePaint.setPathEffect(effects);
canvas.drawPath(linePath, linePaint);

下方的豎線可以根據每天步數動態計算高度。

屬性動畫

可以使用 ValueAnimator 讓步數、排名與圓弧角度從 0 逐漸過渡到目標值。

ValueAnimator walkAnimator = ValueAnimator.ofInt(0, mySize);
walkAnimator.addUpdateListener(animation -> {
    walkNum = (int) animation.getAnimatedValue();
    postInvalidate();
});

ValueAnimator arcAnimator = ValueAnimator.ofFloat(0, arcTarget);
arcAnimator.addUpdateListener(animation -> {
    arcNum = (float) animation.getAnimatedValue();
    postInvalidate();
});

AnimatorSet animSet = new AnimatorSet();
animSet.setDuration(3000);
animSet.playTogether(walkAnimator, arcAnimator);
animSet.start();

自定義 View 的關鍵在於先理清層次與坐標。建議在繪製前先在紙上畫出大致結構,標注各部分的起點與比例,再逐步用 Canvas 實現。這樣可以讓代碼更清晰,也更容易維護。

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