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

自定義 View 之 ProgressBar:測量、繪制與自定義屬性一次講透

編輯:關於 Android 程式設計

這次要動手做一個圓形的 ProgressBar。順便把自定義 View 裡兩個繞不開的知識點講清楚:View 的測量與自定義屬性。

先看效果:

一、準備工作:先想清楚需要哪些變量

新建一個類繼承 View,把要用的成員先聲明出來:

/** View 默認的寬 */
private static final int DEFAULT_WIDTH = 100;
/** View 默認的高 */
private static final int DEFAULT_HEIGHT = 100;
/** 外層圓圈的線條寬度 */
private int stroke = 7;
/** 外層圓圈的線條顏色 */
private int circleColor = Color.BLACK;
/** 內外圓圈之間的間距 */
private int padding = 20;
/** 內層扇形的顏色 */
private int sweepColor = Color.RED;
/** 開始繪制的角度 */
private int startAngle = -90;
/** 已經繪制的角度 */
private int sweepAngle = 0;
/** 每次增長的度數 */
private int sweepStep = 1;

private Paint paint;
private RectF rectF;

構造方法照舊三層遞 ourselves,把初始化集中在最深處:

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

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

public MyProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    paint = new Paint();
    paint.setAntiAlias(true);
}

二、繪制:一個圓環 + 一個扇形

1. 畫外圈圓環

paint.setColor(circleColor);
paint.setStrokeWidth(stroke);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(getWidth() / 2, getHeight() / 2,
        (float) (getWidth() / 2 - Math.ceil(stroke / 2.0)), paint);

drawCircle 的四個參數依次是圓心 x、圓心 y、半徑、畫筆。這裡半徑為什麼要減掉半個線寬?因為系統繪制描邊時,線寬是以路徑為中心向兩側均分的,一半算在半徑內、一半算在外。如果不補償,圓環就會被畫布裁掉一小塊。

2. 畫內部扇形

paint.setColor(sweepColor);
paint.setStyle(Paint.Style.FILL);

rectF = new RectF(padding, padding,
        getWidth() - padding, getHeight() - padding);

canvas.drawArc(rectF, startAngle, sweepAngle, true, paint);

sweepAngle += sweepStep;
sweepAngle = sweepAngle > 360 ? 0 : sweepAngle;
invalidate();

drawArc 的四個參數:扇形所在的矩形、起始角度、掃描角度、是否連圓心。最後調用 invalidate() 請求重繪,動畫就出來了。

三、麻煩來了:wrap_content 下顯示異常

把這個控件丟進布局文件:

<lenve.myprogressbar.MyProgressBar
    android:layout_width="128dp"
    android:layout_height="128dp" />

寫死尺寸沒問題,可一旦改成 wrap_content 或 match_parent,界面就亂了。根源在於:我們的 onDraw 直接用了 getWidth()、getHeight(),而此時系統並不知道該給這個自定義 View 多大——這就需要重寫 onMeasure。

四、View 的測量機制

onMeasure 接收 widthMeasureSpec 與 heightMeasureSpec 兩個參數,它們是 32 位整數:高 2 位表示測量模式,低 30 位表示測量值。模式有三種:

1. EXACTLY(精確模式):布局中寫了具體數值或 match_parent;
2. AT_MOST(最大值模式):布局中寫了 wrap_content;
3. UNSPECIFIED:多見於 ScrollView 之類需要無限延伸的容器。

MeasureSpec 類提供了兩個靜態方法用來拆解:

int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);

拿到之後做一個簡單判斷:用戶明確指定了尺寸就不插手;否則給一個默認值。由於我們畫的是圓,還要強制寬高相等:

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

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    switch (widthMode) {
        case MeasureSpec.EXACTLY:
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.UNSPECIFIED:
            widthSize = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, DEFAULT_WIDTH,
                    getResources().getDisplayMetrics());
            break;
    }

    switch (heightMode) {
        case MeasureSpec.EXACTLY:
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.UNSPECIFIED:
            heightSize = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, DEFAULT_HEIGHT,
                    getResources().getDisplayMetrics());
            break;
    }

    // 圓必須等寬等高
    widthSize = heightSize = Math.min(widthSize, heightSize);

    setMeasuredDimension(widthSize, heightSize);
}

注意 applyDimension 的用法——它把 dp 換算成實際像素,直接拿常量當默認值在多分辨率下會失真。最後必須調用 setMeasuredDimension 把結果告訴系統,否則會拋異常。

五、自定義屬性:讓顏色可以寫在 XML 裡

如果所有顏色都硬編碼在 Java 裡,換個主題就得改代碼。解決辦法是定義自定義屬性。先在 res/values/ 下新建 attrs.xml:

<resources>
    <declare-styleable name="MyProgressBar">
        <attr name="circleColor" format="color" />
        <attr name="sweepColor" format="color" />
        <attr name="stroke" format="dimension" />
        <attr name="mypb_padding" format="dimension" />
        <attr name="startAngle" format="integer" />
        <attr name="sweepStep" format="integer" />
    </declare-styleable>
</resources>

declare-styleable 的 name 強烈建議與自定義 View 的類名一致,這樣在布局文件裡寫屬性時 IDE 才會給提示。

format 的十種取值:

1. boolean——布爾值
2. string——文本
3. color——顏色
4. dimension——尺寸
5. enum——枚舉,如 orientation="horizontal"
6. flag——可按位或,如 layout_gravity="left|bottom"
7. fraction——分數
8. float——浮點數
9. integer——整數
10. reference——引用另一個資源

使用起來就是這樣:

<lenve.myprogressbar.MyProgressBar
    android:layout_width="128dp"
    android:layout_height="128dp"
    app:circleColor="#10ff03"
    app:sweepColor="#0184ff"
    app:stroke="10dp"
    app:mypb_padding="30dp"
    app:startAngle="0"
    app:sweepStep="2" />

然後回到構造方法把值讀出來:

public MyProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    paint = new Paint();
    paint.setAntiAlias(true);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyProgressBar);
    circleColor = ta.getColor(R.styleable.MyProgressBar_circleColor, circleColor);
    sweepColor = ta.getColor(R.styleable.MyProgressBar_sweepColor, sweepColor);
    startAngle = ta.getInt(R.styleable.MyProgressBar_startAngle, startAngle);
    sweepStep = ta.getInt(R.styleable.MyProgressBar_sweepStep, sweepStep);
    stroke = (int) ta.getDimension(R.styleable.MyProgressBar_stroke, stroke);
    padding = (int) ta.getDimension(R.styleable.MyProgressBar_mypb_padding, padding);
    ta.recycle();
}

每個 getXxx 的第二個參數都是默認值——用戶沒寫就用它兜底。用完記得 recycle(),不然會造成內存浪費。

最終效果:

回顧

一個完整的自定義 View 通常要過三道關:onMeasure 決定尺寸,onDraw 負責繪制,自定義屬性負責可配置性。這三者齊備,控件才算真正「拿得出手」,能像系統控件一樣被靈活複用。

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