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

自訂 View 實作:帶百分比文字的圆環 ProgressBar

編輯:關於 Android 程式設計

先放幾張實作出來的效果圖,有興趣的再往下看。

先分析差異

前四張的自訂 ProgressBar 沒有把文字包進去,文字是在 XML 裡另外疊上去的;最後一張則是文字與進度條定義在一起。仔細看會發現幾種變化:

情況一:自訂控制項不含文字

這種做法最省事,用 RelativeLayout 把 TextView 與自訂 View 前後包起來即可。以下是頁面版面,自訂的 View 名為 RoundProgressBar:

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

    <com.fang.zrf.wifidemo.widget.RoundProgressBar
        android:id="@+id/progress"
        android:layout_centerInParent="true"
        android:layout_height="100dp"
        android:layout_width="100dp" />

    <TextView
        android:id="@+id/tv"
        android:gravity="center"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />
</RelativeLayout>

程式碼中,點擊確定鈕使百分比變動後,同步更新文字內容:

mProgress.setCurrentProgress(Integer.valueOf(mEdit.getText().toString()));
mTv.setText("已完成" + "\n" + mProgress.getPercent() + "%");

這種做法的好處是文字呈現相對自由,不必自己用畫筆算座標。

情況二:useCenter 決定要不要連圓心一起畫

像圖 2 那種「有填充又同時有圓環」的樣子,個人覺得視覺上有點擁擠,不如圖 4 清爽。想忽略圓心,只要在畫弧時把 useCenter 傳入 false:

/**
 * @param oval        定義弧線形狀與範圍的矩形
 * @param startAngle  起始角度(度)
 * @param sweepAngle  掃過的角度(度),順時針為正,也就是你要畫的百分比弧長
 * @param useCenter   若為 true,會把圓心納入弧線並閉合,畫出來像一塊派;
 *                    若為 false,則只畫弧線本身
 * @param paint       繪製用的畫筆
 */
canvas.drawArc(rectF, 0, 360 * currentProgress / maxProgress, false, paint);

情況三:空心與實心由 Paint.Style 決定

有了上面的分析,圖 3、圖 4 傳入的 useCenter 就是 true。而圖 1、圖 3 是空心無填充,圖 2、圖 4 是實心有填充,差別在畫筆的 style:

paint.setStyle(Paint.Style.STROKE);  // 空心,只描邊
paint.setStyle(Paint.Style.FILL);    // 實心,帶填充

開始自訂

先把需求拆開(把圖 5 的情況一併考慮進來,不需要時註掉即可):

要畫一個圓環底色 —— 需要顏色、畫筆、環寬;
要依百分比畫一段弧 —— 需要弧色、最大值、目前值;
要決定空心或實心 —— 就是 style;
要畫中間的文字 —— 需要文字顏色、字級、是否顯示;
以上都要處理座標計算。

步驟一:繼承 View

public class RoundProgressBar extends View

步驟二:定義屬性

private Paint paint;            // 畫筆
private int ringColor;          // 圓環顏色
private int ringProgressColor;  // 進度弧顏色
private int textColor;          // 百分比文字顏色
private float textSize;         // 百分比文字大小
private float ringWidth;        // 圓環寬度
private int maxProgress;        // 進度最大值
private int currentProgress;    // 目前進度
private boolean textIsDisplay;  // 是否顯示中間百分比
private int styleRes;           // 進度風格(空心 / 實心)

步驟三:建構子與屬性解析

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

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

public RoundProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    paint = new Paint();
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar);
    ringColor = typedArray.getColor(R.styleable.RoundProgressBar_ringColor, Color.BLACK);
    ringProgressColor = typedArray.getColor(R.styleable.RoundProgressBar_ringProgressColor, Color.RED);
    textColor = typedArray.getColor(R.styleable.RoundProgressBar_textColor, Color.BLUE);
    textSize = typedArray.getDimension(R.styleable.RoundProgressBar_textSize, 14);
    textIsDisplay = typedArray.getBoolean(R.styleable.RoundProgressBar_textIsDisplay, true);
    styleRes = typedArray.getInt(R.styleable.RoundProgressBar_style, 1);
    typedArray.recycle();
}

這裡用到了自訂風格 RoundProgressBar,需要在 values 目錄下新增資源檔宣告:

<resources>
    <declare-styleable name="RoundProgressBar">
        <attr name="ringColor" format="color" />
        <attr name="ringProgressColor" format="color" />
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
        <attr name="textIsDisplay" format="boolean" />
        <attr name="style">
            <enum name="STROKE" value="0" />
            <enum name="FILL" value="1" />
        </attr>
    </declare-styleable>
</resources>

步驟四:覆寫 onDraw

初始化完成,拿起畫筆開始畫。先畫圓環底:

int center = getWidth() / 2;                       // 圓心座標
int radius = (int) (center - ringWidth / 2);       // 半徑要扣掉半個環寬,避免描邊被裁掉
paint.setColor(ringColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(ringWidth);
paint.setAntiAlias(true);
canvas.drawCircle(center, center, radius, paint);

畫圓只需要兩個要素:圓心座標與半徑。

順帶一提,這種算法下在 XML 用 padding 是沒作用的,因為原點固定在 View 左上角。要讓 padding 生效,必須自己從半徑裡扣掉:

int padding = Math.min(getPaddingLeft(), getPaddingTop());
int radius = (int) (center - ringWidth / 2 - padding);

接著畫進度弧:

paint.setStrokeWidth(ringWidth);
paint.setColor(ringProgressColor);

RectF rectF = new RectF(center - radius, center - radius,
                        center + radius, center + radius);

switch (styleRes) {
    case STROKE:
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawArc(rectF, 0, 360 * currentProgress / maxProgress, true, paint);
        break;
    case FILL:
        paint.setStyle(Paint.Style.FILL);
        if (currentProgress != 0) {
            canvas.drawArc(rectF, 0, 360 * currentProgress / maxProgress, false, paint);
        }
        break;
}

最後畫文字,這部分相對簡單:

paint.setStrokeWidth(0);
paint.setColor(textColor);
paint.setTextSize(textSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);

int percent = (int) (((float) currentProgress / (float) maxProgress) * 100);
float textWidth = paint.measureText(percent + "%");
Paint.FontMetrics fm = paint.getFontMetrics();
float textHeight = (float) Math.ceil(fm.descent - fm.top);

if (textIsDisplay && percent != 0 && styleRes == STROKE) {
    // 橫座標 center - textWidth/2、縱座標 center + textHeight/2,讓文字水平垂直居中
    canvas.drawText(percent + "%", center - textWidth / 2, center + textHeight / 2, paint);
}

至此,一個帶百分比的圆環 ProgressBar 就完成了。

回想一下,面試常被問「自訂 View 至少要實作哪些方法」—— 不就是建構子與 onDraw 嗎。當然,實際專案裡還需要 setter 在變更進度後呼叫 invalidate() 觸發重繪,這一步別漏掉。

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