編輯:關於 Android 程式設計
項目裡需要展示份額分佈,於是決定自己畫一個餅圖。直接搬 GitHub 上的 android-charts 又發現它本身帶著一些毛病——最典型的是文字偶爾會錯位,標籤壓到圓外或者互相重疊。折騰之後索性做了一輪精簡和修正,把改好的代碼貼在這裡,需要的同學可以直接複製進項目。
先準備數據集合,每個條目由「標題 + 數值 + 顏色」構成,然後一次性塞給 PieChart:
mData[0] = new ArrayList();
for (int i = 0; i < 5; i++) {
mData[0].add(new TitleValueColorEntity(
mTitle[i], needTime[i], this.getResources().getColor(mColorsId[i])));
}
mPieChart.setData(mData[2]);
其中 TitleValueColorEntity 繼承自 TitleValueEntity,只是在「標題 + 數值」的基礎上多了一個顏色字段,用來決定該扇形的填充色。

這套代碼一共拆成四個類,職責非常清晰:
繼承 View 並重寫 onMeasure(),根據父容器給出的測量模式計算自身尺寸。這樣做的好處是後續所有圖表都能複用同一套測量邏輯:
public class BaseChart extends View {
public BaseChart(Context context) {
super(context);
}
public BaseChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BaseChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = specSize;
}
return result;
}
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = specSize;
}
return result;
}
}
onDraw() 的節奏很簡單:先算出安全邊界與半徑,再畫底圈,最後畫數據。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 取寬高中較小的一邊作為安全矩形,保證圓不會被裁掉
int rect = super.getWidth() > super.getHeight()
? super.getHeight() : super.getWidth();
// 半徑留出 10% 邊距,避免描邊貼邊
radiusLength = (int) ((rect / 2f) * 0.90);
// 圓心置於畫布中心
position = new Point((int) (getWidth() / 2f), (int) (getHeight() / 2f));
drawCircle(canvas);
drawData(canvas);
}
畫扇形時的關鍵是「角度累加」。先用 -90 度作為起始偏移(這樣 12 點鐘方向就是第一塊的起點),然後按數值佔比換算成 sweep 角度,畫完一塊就把 offset 往後推:
protected void drawData(Canvas canvas) {
if (null != data) {
float sum = 0;
for (int i = 0; i < data.size(); i++) {
sum = sum + data.get(i).getValue();
}
Paint mPaintFill = new Paint();
mPaintFill.setStyle(Style.FILL);
mPaintFill.setAntiAlias(true);
Paint mPaintBorder = new Paint();
mPaintBorder.setStyle(Style.STROKE);
mPaintBorder.setColor(radiusColor);
mPaintBorder.setAntiAlias(true);
int offset = -90;
for (int j = 0; j < data.size(); j++) {
TitleValueColorEntity e = data.get(j);
mPaintFill.setColor(e.getColor());
RectF oval = new RectF(position.x - radiusLength, position.y - radiusLength,
position.x + radiusLength, position.y + radiusLength);
int sweep = Math.round(e.getValue() / sum * 360f);
canvas.drawArc(oval, offset, sweep, true, mPaintFill);
canvas.drawArc(oval, offset, sweep, true, mPaintBorder);
offset = offset + sweep;
}
// 標註繪製見下文
}
}
原來的文字定位沒有考慮標籤自身的寬度,導致文字經常跑出扇形之外或者壓線。改造後的做法是先按三角函數算出扇形中點方向的錨位,再根據錨位在圓心的左側還是右側、上半還是下半,分別決定文字對齊方式和基線偏移。同時對佔比過小的扇形(小於 20%)額外增加偏移量,避免文字擠成一團:
float sumvalue = 0f;
for (TitleValueColorEntity e : data) {
float value = e.getValue();
sumvalue = sumvalue + value;
float rate = (sumvalue - value / 2) / sum;
float percentage = (int) (value / sum * 10000) / 100f;
float offsetX = (float) (position.x - radiusLength * 0.5 * Math.sin(rate * -2 * Math.PI));
float offsetY = (float) (position.y - radiusLength * 0.5 * Math.cos(rate * -2 * Math.PI));
Paint mPaintFont = new Paint();
mPaintFont.setColor(Color.WHITE);
mPaintFont.setTextSize(MyUtils.sp2px(getContext(), 15));
mPaintFont.setAntiAlias(true);
String title = e.getTitle();
float realx = 0;
float realy = 0;
// 依據錨點相對圓心的方位決定文字對齊方式
if (offsetX < position.x) {
realx = offsetX - mPaintFont.measureText(title) - 5;
} else if (offsetX > position.x) {
realx = offsetX + 5;
} else {
realx = offsetX - (mPaintFont.measureText(title) / 2);
}
// 小佔比扇形額外讓位,避免標籤重疊
if (offsetY >= position.y) {
realy = (value / sum < 0.2f) ? offsetY + 10 : offsetY + 5;
} else {
realy = (value / sum < 0.2f) ? offsetY - 10 : offsetY + 5;
}
if (percentage != 0.0f) {
canvas.drawText(title, realx, realy, mPaintFont);
canvas.drawText(String.valueOf((int) value) + " min",
realx, realy + MyUtils.sp2px(getContext(), 15), mPaintFont);
canvas.drawText(String.valueOf(percentage) + "%",
realx, realy + MyUtils.sp2px(getContext(), 30), mPaintFont);
}
}
三行文字按 15dp 的行距依次向下排開,分別是標題、原始數值和百分比。佔比為 0 的扇形直接不畫文字,讓畫面更乾淨。
兩個實體類都很輕薄,只是承載數據:
public class TitleValueEntity {
private String title;
private float value;
public TitleValueEntity(String title, float value) {
this.title = title;
this.value = value;
}
public TitleValueEntity() { }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public float getValue() { return value; }
public void setValue(float value) { this.value = value; }
}
public class TitleValueColorEntity extends TitleValueEntity {
private int color;
public TitleValueColorEntity(String title, float value, int color) {
super(title, value);
this.color = color;
}
public TitleValueColorEntity() { super(); }
public int getColor() { return color; }
public void setColor(int color) { this.color = color; }
}
第一,餅圖一定要開抗鋸齒(setAntiAlias(true)),否則圓弧邊緣會出現明顯鋸齒。
第二,扇形之間靠 1~2px 的描邊分隔比留白更省事,视觉上更整齊。
第三,如果扇形數量超過六七個,強烈建議改用環圖加圖例的組合,直接在扇區上堆文字無論怎麼調都會顯得擁擠。
第四,這套代碼所有數值都是基於實際測量尺寸動態計算的,所以在橫豎屏切換、不同 dpi 設備上都能自適應,不需要為每種屏幕單獨寫死參數。
Android 應用安裝流程解析
了解 Android 應用的安裝流程,有助於除錯、發版與理解系統行為。本文從打包、簽名到安裝路徑做一項整理。 從原始碼到 APK Android 專案會先將 Java
Android源碼解析(二十三)——深入剖析App崩潰與異常處理流程
在之前的系列文章中,我們先後探討了Android各類窗口的顯示機制,包括Activity、Dialog、PopupWindow以及Toast的加載與繪制過程。歸根結底,整
Android流量不夠用?五個設定有效省下數據
想節省Android流量,可從五處著手:開啟Chrome流量節省、關閉不需要的帳戶同步、設定流量限制與背景資料限制、關閉自動更新或僅Wi-Fi更新、使用離線地圖。 限制背
微信公眾平台手機版上線:功能、登入與限制
微信公眾平台手機版以HTML5方式提供基本營運功能,可查看消息、評論、粉絲數、贊賞,也能群發與編輯文章。 目前功能仍較精簡,沒有自訂菜單與自動回覆,但適合隨時回覆訊息與查