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

自訂漸層色進度條:不靠系統 ProgressBar 的 SpringProgressView

編輯:關於 Android 程式設計

某天在論壇上看到有人徵求「自訂漸層色進度條」的寫法,那張效果圖看起來確實漂亮,於是就動手做了一個。

這個自訂 View 完全脫離了 Android 內建的 ProgressBar,而且沒有使用任何一張圖片,全部靠 Canvas 即時繪製。這麼做的好處很直接:不會因為解像度不同而模糊,也不會因為換色或改比例而需要重新切圖,控制項的耦合度降到最低。

核心程式碼

public class SpringProgressView extends View {

    /** 分段顏色:綠 → 黃 → 紅 */
    private static final int[] SECTION_COLORS = {
        Color.GREEN, Color.YELLOW, Color.RED };

    private float maxCount;      // 進度條最大值
    private float currentCount;  // 當前值
    private Paint mPaint;
    private int mWidth, mHeight;

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

    public SpringProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SpringProgressView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        int round = mHeight / 2;

        // 最外層底色
        mPaint.setColor(Color.rgb(71, 76, 80));
        canvas.drawRoundRect(new RectF(0, 0, mWidth, mHeight), round, round, mPaint);

        // 內層黑色底襯
        mPaint.setColor(Color.BLACK);
        canvas.drawRoundRect(new RectF(2, 2, mWidth - 2, mHeight - 2), round, round, mPaint);

        // 進度本體
        float section = currentCount / maxCount;
        RectF rectProgress = new RectF(3, 3, (mWidth - 3) * section, mHeight - 3);

        if (section <= 1.0f / 3.0f) {
            mPaint.setColor(section == 0.0f ? Color.TRANSPARENT : SECTION_COLORS[0]);
        } else {
            int count = (section <= 2.0f / 3.0f) ? 2 : 3;
            int[] colors = new int[count];
            System.arraycopy(SECTION_COLORS, 0, colors, 0, count);

            float[] positions = new float[count];
            positions[0] = 0.0f;
            positions[positions.length - 1] = 1.0f;
            if (count == 3) {
                positions[1] = (maxCount / 3) / currentCount;
            }

            mPaint.setShader(new LinearGradient(
                    3, 3, (mWidth - 3) * section, mHeight - 3,
                    colors, positions, Shader.TileMode.MIRROR));
        }
        canvas.drawRoundRect(rectProgress, round, round, mPaint);
    }

    public void setMaxCount(float maxCount) {
        this.maxCount = maxCount;
    }

    public void setCurrentCount(float currentCount) {
        this.currentCount = currentCount > maxCount ? maxCount : currentCount;
        invalidate();   // 數值變了就重畫
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        mWidth = (widthSpecMode == MeasureSpec.EXACTLY
                || widthSpecMode == MeasureSpec.AT_MOST) ? widthSpecSize : 0;

        mHeight = (heightSpecMode == MeasureSpec.AT_MOST
                || heightSpecMode == MeasureSpec.UNSPECIFIED)
                ? dipToPx(15) : heightSpecSize;

        setMeasuredDimension(mWidth, mHeight);
    }

    private int dipToPx(int dip) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }
}

四個設計要點

1. 進度本質上就是一個比例。進度條沒有什麼奧妙,就是 currentCount / maxCount 這個介於 0 到 1 之間的數字,乘上可用寬度就是實際要畫多長。

2. 圓角靠 drawRoundRect。把圓角半徑設成高度的一半(mHeight / 2),就會得到膠囊狀的頭尾,這也是它看起來比較「軟」的原因。

3. 漸層色用 LinearGradient 渲染。這是最需要動腦筋的部分,因為顏色位置必須換算成「相對於目前進度寬度」的比例:

  • 進度在三分之一以下:只顯示綠色一種;
  • 超過三分之一但不到三分之二:綠、黃兩色;
  • 超過三分之二:綠、黃、紅三色全上。

三色各佔總進度的三分之一,因此要把它們映射到「目前畫出來的這段寬度」上,位置值就得據此重算。這其實就是一道比例問題,畫個圖把線段標上刻度會清楚很多。

4. 兩層圓角矩形疊出立體感。第一個是外框底色,第二個內縮 2px 當黑色襯底,第三個再內縮 1px 當進度本體。三層疊起來就有內凹的視覺效果,完全不需要 Nine-patch 圖。

心得

做自訂控制項最難的其實不是語法,而是「看到效果圖能反推出實作步驟」。程式碼永遠是第二步,第一步是把圖形拆解成「幾層、每層什麼顏色、尺寸怎麼算」。卡住的时候就拿起紙筆一格一格標數字,久了自然就有手感。否則只背 API,遇到沒見過的設計稿就只能紙上談兵。

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