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

Android 自定義控件(三):實現圓環式的百分比顯示

編輯:關於 Android 程式設計

最近一直在啃自定義控件。昨天群裡有人問圓盤樣式的百分比該怎麼畫,正好學有所用,於是就有了這篇記錄。

先看效果,一目了然:

這裡的顯示顏色、每一段佔據的角度,都可以在布局里自行指定。示例中用了三種顏色,對應三段不同的角度。

第一步:定義自定義屬性

既然要做成可配置的控件,就得先在 attrs.xml 中聲明屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomCircle">
        <attr name="firstColor" format="color" />
        <attr name="secondColor" format="color" />
        <attr name="thirdColor" format="color" />
        <attr name="firstAngle" format="integer" />
        <attr name="secondAngle" format="integer" />
        <attr name="thirdAngle" format="integer" />
    </declare-styleable>
</resources>

第二步:在構造方法中取值

聲明了屬性,就要把它們讀出來並賦值。這一步通過 TypedArray 完成,取完記得 recycle():

TypedArray mArray = context.obtainStyledAttributes(attrs, R.styleable.CustomCircle, defStyleAttr, 0);
firstColor = mArray.getColor(R.styleable.CustomCircle_firstColor, Color.BLUE);
secondColor = mArray.getColor(R.styleable.CustomCircle_secondColor, Color.GREEN);
thirdColor = mArray.getColor(R.styleable.CustomCircle_thirdColor, Color.RED);
firstAngle = mArray.getInt(R.styleable.CustomCircle_firstAngle, 90);
secondAngle = mArray.getInt(R.styleable.CustomCircle_secondAngle, 180);
thirdAngle = mArray.getInt(R.styleable.CustomCircle_thirdAngle, 120);
mArray.recycle();

第三步:重寫 onDraw 畫圖

這是整個控件的核心。思路是先用一個粗描邊的圓畫出灰色底環,再用 drawArc() 依次把三段彩色扇形疊上去。關鍵在於 setStrokeWidth(center)——把筆觸寬度設成半徑,這樣描邊的圓看起來就是一個實心的圓環。

@Override
protected void onDraw(Canvas canvas) {
    int center = getWidth() / 2;
    int radius = center / 2;
    mPaint.setColor(Color.GRAY);
    mPaint.setStrokeWidth(center);
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.STROKE);
    canvas.drawCircle(center, center, radius, mPaint);

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

    mPaint.setColor(firstColor);
    canvas.drawArc(rectF, 0, firstAngle, false, mPaint);

    mPaint.setColor(secondColor);
    canvas.drawArc(rectF, firstAngle, secondAngle, false, mPaint);

    mPaint.setColor(thirdColor);
    canvas.drawArc(rectF, secondAngle, thirdAngle, false, mPaint);
}

第四步:在布局中使用

<com.sdufe.thea.guo.view.CustomCircle
    android:layout_width="300dp"
    android:layout_height="300dp"
    custom:firstangle="60"
    custom:firstcolor="@android:color/holo_purple"
    custom:secondangle="180"
    custom:secondcolor="@android:color/holo_blue_bright"
    custom:thirdangle="120"
    custom:thirdcolor="@android:color/holo_orange_light" />

這裡要留意 custom 這個命名空間,它不是系統默認的,需要在布局根節點上提前聲明:

xmlns:custom="https://schemas.android.com/apk/res/你的包名"

寫到這裡,一個可配置的圓環百分比控件就完成了。

最後分享一點心得:當你看不懂別人代碼的執行邏輯時,最好的辦法就是跟進調試(debug),一步一步看變量的變化,比盯著代碼發呆有效得多。

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