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

自定義 View 實作教學:帶小圓點的倒數計時圓形進度條

編輯:關於 Android 程式設計

上一篇我們做了一個可以隨時暫停的圓形進度條,這次換個花樣,來做一個「外圈是倒數計時、弧線末端還跟著一顆小圓點」的 View。整個元件裡最麻煩的地方,就在於那顆小圓必須隨著進度弧一起跑,也就是說,我們得隨時算出它的座標。

網路上-linejoin 大神曾經用「小圓落在第一象限、第二象限……分成四種case 分別處理」的方式來解 this 問題,思路沒錯,但公式一堆、註解又少,讀起來實在吃力。後來社群裡的 yissan 給了我一個關鍵提示:直接根據進度算出小圓的 x、y 座標。於是我把課本重新翻出來,把弧度、正弦 sinα、餘弦 cosα 溫習一遍,最後用很精簡的算式把這顆小圓畫了出來。這裡要特別感謝 yissan 的思路,也感謝原作者提供的創意,我在他的基礎上把座標計算大幅簡化了。

廢話不多說,先看成果:

接下來就照著自定義 View 的「五步走」流程,把這個效果做出來。

自定義 View 的五個步驟

依 Android Developers 官網的說明,自定義控制項大致可以拆成下列五步,實作時可依需求省略部分環節:

1. 建立 View

2. 處理 View 的版面配置(測量)

3. 繪製 View

4. 與使用者互動

5. 優化已定義的 View

第一步:建立 View

定義自定義屬性

先在 res/values 底下新增一個 attr.xml,把要用到的樣式屬性宣告出來:外圈的實心色、邊框色、邊框寬度、半徑,進度弧的顏色與寬度,小圓的實心色、邊框色、邊框寬度、半徑,最後是中央文字的顏色與字級。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CountDownProgress">
        <!-- 預設圓 -->
        <attr name="default_circle_solide_color" format="color" />
        <attr name="default_circle_stroke_color" format="color" />
        <attr name="default_circle_stroke_width" format="dimension" />
        <attr name="default_circle_radius" format="dimension" />
        <!-- 進度弧 -->
        <attr name="progress_color" format="color" />
        <attr name="progress_width" format="dimension" />
        <!-- 小圓 -->
        <attr name="small_circle_solide_color" format="color" />
        <attr name="small_circle_stroke_color" format="color" />
        <attr name="small_circle_stroke_width" format="dimension" />
        <attr name="small_circle_radius" format="dimension" />
        <!-- 文字 -->
        <attr name="text_color" format="color" />
        <attr name="text_size" format="dimension" />
    </declare-styleable>
</resources>

在自定義 View 中讀取屬性

建構子裡用 TypedArray 把上面宣告的屬性一一取出。這裡有個小技巧:與其逐項去 get,不如搭配 getIndexCount() 與 switch 遍歷,之後要擴充屬性也好維護。

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

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

public CountDownProgress(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CountDownProgress);
    int indexCount = typedArray.getIndexCount();
    for (int i = 0; i < indexCount; i++) {
        int attr = typedArray.getIndex(i);
        switch (attr) {
            case R.styleable.CountDownProgress_default_circle_radius:
                defaultCircleRadius = (int) typedArray.getDimension(attr, defaultCircleRadius);
                break;
            case R.styleable.CountDownProgress_default_circle_solide_color:
                defaultCircleSolideColor = typedArray.getColor(attr, defaultCircleSolideColor);
                break;
            case R.styleable.CountDownProgress_default_circle_stroke_color:
                defaultCircleStrokeColor = typedArray.getColor(attr, defaultCircleStrokeColor);
                break;
            case R.styleable.CountDownProgress_default_circle_stroke_width:
                defaultCircleStrokeWidth = (int) typedArray.getDimension(attr, defaultCircleStrokeWidth);
                break;
            case R.styleable.CountDownProgress_progress_color:
                progressColor = typedArray.getColor(attr, progressColor);
                break;
            case R.styleable.CountDownProgress_progress_width:
                progressWidth = (int) typedArray.getDimension(attr, progressWidth);
                break;
            case R.styleable.CountDownProgress_small_circle_radius:
                smallCircleRadius = (int) typedArray.getDimension(attr, smallCircleRadius);
                break;
            case R.styleable.CountDownProgress_small_circle_solide_color:
                smallCircleSolideColor = typedArray.getColor(attr, smallCircleSolideColor);
                break;
            case R.styleable.CountDownProgress_small_circle_stroke_color:
                smallCircleStrokeColor = typedArray.getColor(attr, smallCircleStrokeColor);
                break;
            case R.styleable.CountDownProgress_small_circle_stroke_width:
                smallCircleStrokeWidth = (int) typedArray.getDimension(attr, smallCircleStrokeWidth);
                break;
            case R.styleable.CountDownProgress_text_color:
                textColor = typedArray.getColor(attr, textColor);
                break;
            case R.styleable.CountDownProgress_text_size:
                textSize = (int) typedArray.getDimension(attr, textSize);
                break;
            default:
                break;
        }
    }
    typedArray.recycle();
    setPaint();
}

建立畫筆

畫筆一定要在 onDraw() 之外建立,避免每幀都 new 物件造成不必要的 GC。這裡總共準備五支畫筆:預設圓邊框、進度弧、小圓邊框、小圓實心、文字。

private void setPaint() {
    // 預設圓(先畫邊框)
    defaultCriclePaint = new Paint();
    defaultCriclePaint.setAntiAlias(true);
    defaultCriclePaint.setDither(true);
    defaultCriclePaint.setStyle(Paint.Style.STROKE);
    defaultCriclePaint.setStrokeWidth(defaultCircleStrokeWidth);
    defaultCriclePaint.setColor(defaultCircleStrokeColor);

    // 進度弧
    progressPaint = new Paint();
    progressPaint.setAntiAlias(true);
    progressPaint.setDither(true);
    progressPaint.setStyle(Paint.Style.STROKE);
    progressPaint.setStrokeWidth(progressWidth);
    progressPaint.setColor(progressColor);
    progressPaint.setStrokeCap(Paint.Cap.ROUND); // 圓頭筆刷,線段端點才不會是平的

    // 小圓邊框
    smallCirclePaint = new Paint();
    smallCirclePaint.setAntiAlias(true);
    smallCirclePaint.setDither(true);
    smallCirclePaint.setStyle(Paint.Style.STROKE);
    smallCirclePaint.setStrokeWidth(smallCircleStrokeWidth);
    smallCirclePaint.setColor(smallCircleStrokeColor);

    // 小圓實心(通常給白色,做出「空心圓」的視覺)
    smallCircleSolidePaint = new Paint();
    smallCircleSolidePaint.setAntiAlias(true);
    smallCircleSolidePaint.setDither(true);
    smallCircleSolidePaint.setStyle(Paint.Style.FILL);
    smallCircleSolidePaint.setColor(smallCircleSolideColor);

    // 中央文字
    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setDither(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(textColor);
    textPaint.setTextSize(textSize);
}

第二步:處理版面配置(onMeasure)

如果外部沒有明確指定寬高,我們就依「半徑 × 2 + 最粗的那條線寬 + 內距」自己算一個剛剛好的尺寸;反過來,如果開發者已經給了精確值,就不要多事。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int widthSize;
    int heightSize;
    int strokeWidth = Math.max(defaultCircleStrokeWidth, progressWidth);

    if (widthMode != MeasureSpec.EXACTLY) {
        widthSize = getPaddingLeft() + defaultCircleRadius * 2 + strokeWidth + getPaddingRight();
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
    }
    if (heightMode != MeasureSpec.EXACTLY) {
        heightSize = getPaddingTop() + defaultCircleRadius * 2 + strokeWidth + getPaddingBottom();
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

第三步:繪製 View(onDraw)

先講座標怎麼想。以手機左上角為原點 (0,0),大圓圓心就是 (r, r)。小圓沿著大圓的邊緣跑,我們只要盯著它在幾個關鍵位置(例如 0°、90°、180°、270°)的座標,就能反推出通用公式:

基本的三角關係是 X = cosα × r、Y = sinα × r,而「弧度 = 度數 × π / 180」(在 Android 中 π 用 Math.PI 表示)。把原點從圓心平移到左上角後,小圓圓心的座標規律就變成:

X = sinα × r + r
Y = r − cosα × r

有了這兩條式子,剩下的就只是把角度換算成弧度、代入計算而已。

另外,為了方便取得進度,我們讓這個自定義 View 直接繼承 ProgressBar,就能免費得到 getProgress() 與 getMax(),進度弧掃過的角度即可寫成 getProgress() * 1.0f / getMax() * 360。

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.translate(getPaddingLeft(), getPaddingTop());

    // 預設圓
    canvas.drawCircle(defaultCircleRadius, defaultCircleRadius, defaultCircleRadius, defaultCriclePaint);

    // 進度弧
    currentAngle = getProgress() * 1.0f / getMax() * 360;
    canvas.drawArc(new RectF(0, 0, defaultCircleRadius * 2, defaultCircleRadius * 2),
            mStartSweepValue, currentAngle, false, progressPaint);

    // 中央文字
    String text = getProgress() + "%";
    float textWidth = textPaint.measureText(text);
    float textHeight = (textPaint.descent() + textPaint.ascent()) / 2;
    canvas.drawText(text, defaultCircleRadius - textWidth / 2, defaultCircleRadius - textHeight, textPaint);

    // 小圓
    float currentDegreeFlag = 360 * currentAngle + extraDistance;
    float hudu = (float) Math.abs(Math.PI * currentDegreeFlag / 180); // 度 → 弧度
    float smallCircleX = (float) Math.abs(Math.sin(hudu) * defaultCircleRadius + defaultCircleRadius);
    float smallCircleY = (float) Math.abs(defaultCircleRadius - Math.cos(hudu) * defaultCircleRadius);
    canvas.drawCircle(smallCircleX, smallCircleY, smallCircleRadius, smallCirclePaint);
    canvas.drawCircle(smallCircleX, smallCircleY, smallCircleRadius - smallCircleStrokeWidth, smallCircleSolidePaint);

    canvas.restore();
}

第四步:與使用者互動

如果只是想先驗證弧線流暢度,用 Handler 定時推進度就能動起來:

public class MainActivity extends AppCompatActivity {
    private CountDownProgress countDownProgress;
    private int progress;
    public static final int HANDLER_MESSAGE = 2;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_MESSAGE:
                    progress = countDownProgress.getProgress();
                    countDownProgress.setProgress(++progress);
                    if (progress >= 100) {
                        handler.removeMessages(HANDLER_MESSAGE);
                        progress = 0;
                        countDownProgress.setProgress(0);
                    } else {
                        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE, 100);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        countDownProgress = (CountDownProgress) findViewById(R.id.countdownProgress);
        countDownProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = Message.obtain();
                message.what = HANDLER_MESSAGE;
                handler.sendMessage(message);
            }
        });
    }
}

不過若我們不想繼承 ProgressBar,而是直接繼承 View,那 getProgress() 這些方法就用不上了。這時候改用「屬性動畫」來驅動角度,反而更乾淨:

public void startCountDownTime(final OnCountdownFinishListener countdownFinishListener) {
    setClickable(false);
    ValueAnimator animator = ValueAnimator.ofFloat(0, 1.0f);
    // 動畫時長 = 倒數時間 + 1000ms(原因見下方 CountDownTimer 的說明)
    animator.setDuration(countdownTime + 1000);
    animator.setInterpolator(new LinearInterpolator()); // 等速
    animator.setRepeatCount(0); // 不循環,-1 代表無限

    // ValueAnimator 只對「數值」做運算,跟具體控件無關,
    // 因此必須自己監聽數值變化,再回頭刷新 View
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            // 數值介於 0.0 ~ 1.0,乘上 360 之後剛好掃過一圈
            currentAngle = (float) animation.getAnimatedValue();
            invalidate();
        }
    });
    animator.start();

    animator.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) { }

        @Override
        public void onAnimationEnd(Animator animation) {
            // 倒數結束後,透過自定義回呼把控制權交還給 UI 層
            if (countdownFinishListener != null) {
                countdownFinishListener.countdownFinished();
            }
            setClickable(countdownTime <= 0);
        }

        @Override
        public void onAnimationCancel(Animator animation) { }

        @Override
        public void onAnimationRepeat(Animator animation) { }
    });

    countdownMethod();
}

至於倒數計時本身,我們直接用系統提供的 CountDownTimer。它的建構參數分別是「總時間」與「每隔多久呼叫一次 onTick」,單位都是毫秒。

實測時會發現一個坑:倒數永遠停在 1 秒,走不到 0。翻一下 CountDownTimer 的 start() 原始碼就明白了——當 mMillisInFuture <= 0 時,它會直接跳到 onFinish(),所以我們把總時長多加 1000 毫秒來避開這個問題。

public synchronized final CountDownTimer start() {
    mCancelled = false;
    if (mMillisInFuture <= 0) {
        onFinish();
        return this;
    }
    mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
    mHandler.sendMessage(mHandler.obtainMessage(MSG));
    return this;
}
private void countdownMethod() {
    new CountDownTimer(countdownTime + 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            countdownTime = countdownTime - 1000;
            textDesc = countdownTime / 1000 + "″";
            invalidate();
        }

        @Override
        public void onFinish() {
            textDesc = "時間到";
            // 同步把小圓藏起來
            smallCirclePaint.setColor(getResources().getColor(android.R.color.transparent));
            smallCircleSolidePaint.setColor(getResources().getColor(android.R.color.transparent));
            invalidate();
        }
    }.start();
}

從哪個時刻開始倒數,交由呼叫端決定,所以我們對外開一個 setter:

public void setCountdownTime(long countdownTime) {
    this.countdownTime = countdownTime;
    textDesc = countdownTime / 1000 + "″";
}

倒數結束後總要通知 UI 層後續該做什麼,因此定義一個簡單的監聽介面:

public interface OnCountdownFinishListener {
    void countdownFinished();
}

最後:怎麼用

public class MainActivity extends AppCompatActivity {
    private CountDownProgress countDownProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        countDownProgress = (CountDownProgress) findViewById(R.id.countdownProgress);
        countDownProgress.setCountdownTime(10 * 1000);
        countDownProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownProgress.startCountDownTime(new CountDownProgress.OnCountdownFinishListener() {
                    @Override
                    public void countdownFinished() {
                        Toast.makeText(MainActivity.this, "倒數結束了,該由 UI 處理後續邏輯", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }
}

到這裡,一個會倒數、弧線末端還帶著小圓點的圓形進度條就完成了。關鍵其實只有一句話:把角度換成弧度,用 sin / cos 把極座標轉成直角座標。建議搭配上面的座標圖一起看,會更直觀。

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