編輯:關於 Android 程式設計

模擬器上會有輕微鋸齒,真機顯示與預期一致。
看到這個效果,第一反應應該是:原生控件裡沒有現成東西能做到,那就自己畫。仔細拆一下,這個圓環進度條其實由四層構成:
最底層是一圈淺色的底環;其上是一段隨進度增長的深色圓弧;中間蓋著一個深藍色實心圓;最後在圆心位置寫上百分比文字。前三層都是純圖形,用 Canvas 繪製即可,剩下的事情就是把進度和繪製聯動起來。
(1)自定義 View,重寫構造方法與 onDraw(),找到繪製的時機與畫布。
(2)畫淺色底環。
(3)畫深色進度圓弧。
(4)加入 SeekBar,用它的進度驅動圓弧變化。
(5)畫深藍色實心圓。
(6)畫百分比文字。
(7)擴展:抽出自定義屬性,讓配色、線寬、字號可配置。
public class MyProgressBar extends View {
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);
init();
}
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); }
}
有了這個自定義 View,就可以先在布局裡佔位,同時放一個 SeekBar 作為調試進度的入口:
<com.kedi.myprogressbar.MyProgressBar
android:id="@+id/pg"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_centerInParent="true"
android:padding="5dp" />
<SeekBar
android:id="@+id/sb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/pg"
android:layout_margin="20dp"
android:max="100" />
Paint(畫筆)常用方法:new Paint() 創建;setColor() 設色;setStyle() 設風格(STROKE 描邊、FILL 實心);setStrokeWidth() 設線寬;setAntiAlias() 抗鋸齒;setTextSize()/setTypeface() 控制文字大小與字形。
Canvas(畫布)常用方法:
drawCircle(cx, cy, radius, paint) 畫圓或圓環;drawText(text, x, y, paint) 畫文字;drawArc(oval, startAngle, sweepAngle, useCenter, paint) 畫圓弧。其中 oval 用 RectF(left, top, right, bottom) 描述外接矩形,決定圓弧的大小與形狀;startAngle 為起始角度;sweepAngle 為掃過的角度;useCenter 為 true 時連兩條邊形成扇形,為 false 時只有弧線。

private void init() {
paint = new Paint();
roundW = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics());
}
這裡順手做了 dp 到 px 的換算,避免不同屏幕密度下線寬走形。
核心邏輯是先算圆心和半徑,再設置描邊風格畫圓:
int centerX = getWidth() / 2;
int centerY = centerX;
int radius1 = centerX - roundW / 2;
paint.setColor(Color.parseColor("#11339ED4"));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(roundW);
paint.setAntiAlias(true);
canvas.drawCircle(centerX, centerY, radius1, paint);
半徑要減掉半個線寬,這樣描邊才不會被裁掉。效果如下:

圓弧的關鍵在於起止角度。既然它代表進度,起點固定為 0(十二點鐘方向),終點則隨進度變化:
末端角度 = 360f * progress / maxProgress;
因此我們需要兩個成員變量保存當前進度與最大進度,並對外提供一個更新入口:
public void setProgress(int progress) {
this.progress = progress < 0 ? 0 : progress;
invalidate(); // 觸發重繪
}
繪製部分:
RectF oval = new RectF(centerX - radius1, centerY - radius1,
centerX + radius1, centerY + radius1);
paint.setStrokeWidth(roundW);
paint.setColor(Color.parseColor("#339ED4"));
paint.setStyle(Paint.Style.STROKE);
canvas.drawArc(oval, 0, 360f * progress / maxProgress, false, paint);
效果圖:

思路非常直接:監聽 SeekBar 的進度變化,把新值透過 setProgress() 傳給自定義 View,invalidate() 會觸發 onDraw() 重繪。
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
pg.setProgress(progress);
}
@Override public void onStartTrackingTouch(SeekBar seekBar) {}
@Override public void onStopTrackingTouch(SeekBar seekBar) {}
});

同樣用 drawCircle(),只是把風格換成 FILL:
int radius2 = centerX - roundW;
paint.setColor(Color.parseColor("#336799"));
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(centerX, centerY, radius2, paint);


畫文字需要確定字號、字形、顏色、坐標和內容。百分比由進度換算而來,坐標則要根據圆心和文字自身的寬高做居中處理:
paint.setStrokeWidth(0);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setTextSize(textSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
int percent = (int) (((float) progress / maxProgress) * 100);
float textWidth = paint.measureText(percent + "%");
canvas.drawText(percent + "%",
centerX - textWidth / 2,
centerY + textSize / 2, paint);
到這裡,成品和最初看到的截圖已經沒有差別了。

如果換個項目想換一套配色,難道只能複製一份代碼改常量?那樣的控件太不通用。更好的做法是:把所有與外觀相關的量都提成成員變量,再透過自定義屬性暴露出來。
private int roundW; // 圓環寬度 private int roundColor; // 圓環顏色 private int progress; // 當前進度 private int maxProgress = 100; private int progressColor; // 進度圓弧顏色 private int circleColor; // 實心圓顏色 private int textColor; // 文字顏色 private int textSize; // 文字大小
在 res/values/attrs.xml 中聲明:
<declare-styleable name="MyProgressBarStyle">
<attr name="roundW" format="dimension" />
<attr name="roundColor" format="color" />
<attr name="progress" format="integer" />
<attr name="progressColor" format="color" />
<attr name="circleColor" format="color" />
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
在構造方法中用 TypedArray 取值,並把原本的常量作為默認值:
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyProgressBarStyle);
roundW = (int) a.getDimension(R.styleable.MyProgressBarStyle_roundW,
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
roundColor = a.getColor(R.styleable.MyProgressBarStyle_roundColor, Color.parseColor("#11339ED4"));
progress = a.getInt(R.styleable.MyProgressBarStyle_progress, 0);
progressColor = a.getColor(R.styleable.MyProgressBarStyle_progressColor, Color.parseColor("#339ED4"));
circleColor = a.getColor(R.styleable.MyProgressBarStyle_circleColor, Color.parseColor("#336799"));
textColor = a.getColor(R.styleable.MyProgressBarStyle_textColor, Color.WHITE);
textSize = (int) a.getDimension(R.styleable.MyProgressBarStyle_textSize,
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 25, getResources().getDisplayMetrics()));
a.recycle();
然後把 onDraw() 裡寫死的色值換成成員變量,並為需要動態修改的項提供 Setter(記得在 Setter 末尾調用 invalidate(),否則界面不會刷新)。
先在根布局聲明命名空間 xmlns:my="https://schemas.android.com/apk/res-auto",接著就能寫自定義屬性了:
<com.kedi.myprogressbar.MyProgressBar
android:id="@+id/pg"
android:layout_width="120dp"
android:layout_height="120dp"
my:roundW="8dp"
my:roundColor="#316900"
my:progressColor="#FF6400"
my:circleColor="#ACD900"
my:textColor="#EE3400"
my:textSize="20sp" />


至此,一個足夠靈活、可以複用於不同主題的圓形進度條就完成了。
Android Service 完全解析:兩種啟動方式與生命週期實戰
Service 存在的意義是什麼 很多初學者會疑惑:Service 究竟用來做什麼?作為 Android 四大組件之一,你可以把它理解成「沒有界面的 Activity」—
Android 編譯系統剖析(三):make 的默認編譯流程
本文的目標是徹底摸清「默認編譯整個 Android 系統」時的程式碼流程。 當我們執行 make 時,它會查找並執行當前的 Makefile。在 Android 頂層源碼
Android Media Framework 總綱:從 Java 層一路走到解碼器
一、Media Framework 的層次結構 從上到下可以切成這幾層: 應用層:Music、VideoPlayer 等 App。 Java 層:MediaPlaye
OPPO R9 怎麼讓 App 在背景長期運行?省電機制的解除設定
ColorOS 3.0 設計了一套省電機制:當系統偵測到某個 App 在背景有耗電行為時,會自動將它關閉或凍結。這對續航是好事,但副作用是——即時通訊、下單通知這類需要常