原專案:https://github.com/limccn/Android-Charts
因為專案裡需要畫餅圖,我對這個庫做了精簡與修改。原庫有些小瑕疵,例如文字偶爾會錯位,這裡已經修掉。把下面的程式碼複製進專案即可使用。
mData[0] = new ArrayList<TitleValueColorEntity>();
for (int i = 0; i < 5; i++) {
mData[0].add(new TitleValueColorEntity(mTitle[i], needTime[i],
this.getResources().getColor(mColorsId[i])));
}
mPieChart.setData(mData[0]);
package com.nekocode.xuedao.piechart;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
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 = Math.min(result, specSize);
}
return result;
}
// measureHeight 與 measureWidth 邏輯相同
}
public class PieChart extends BaseChart {
private List<TitleValueColorEntity> data;
private int radiusLength = 80;
private Point position = new Point(0, 0);
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 取寬高的較小值作為安全區域
int rect = getWidth() > getHeight() ? getHeight() : getWidth();
radiusLength = (int) ((rect / 2f) * 0.90); // 半徑留一點邊距
position = new Point((int) (getWidth() / 2f), (int) (getHeight() / 2f));
drawCircle(canvas);
drawData(canvas);
}
protected void drawCircle(Canvas canvas) {
Paint mPaintCircleBorder = new Paint();
mPaintCircleBorder.setColor(Color.WHITE);
mPaintCircleBorder.setStyle(Style.STROKE);
mPaintCircleBorder.setStrokeWidth(2);
mPaintCircleBorder.setAntiAlias(true);
canvas.drawCircle(position.x, position.y, radiusLength, mPaintCircleBorder);
}
protected void drawData(Canvas canvas) {
if (null == data) return;
// 先求總和
float sum = 0;
for (TitleValueColorEntity e : data) sum += e.getValue();
Paint mPaintFill = new Paint();
mPaintFill.setStyle(Style.FILL); mPaintFill.setAntiAlias(true);
Paint mPaintBorder = new Paint();
mPaintBorder.setStyle(Style.STROKE); mPaintBorder.setAntiAlias(true);
int offset = -90; // 從 12 點方向開始
RectF oval = new RectF(position.x - radiusLength, position.y - radiusLength,
position.x + radiusLength, position.y + radiusLength);
// 逐片畫扇區
for (TitleValueColorEntity e : data) {
mPaintFill.setColor(e.getColor());
int sweep = Math.round(e.getValue() / sum * 360f);
canvas.drawArc(oval, offset, sweep, true, mPaintFill);
canvas.drawArc(oval, offset, sweep, true, mPaintBorder);
offset += sweep;
}
// 標註文字:位置由扇形中線方向推算
float sumvalue = 0f;
Paint mPaintFont = new Paint();
mPaintFont.setColor(Color.WHITE);
mPaintFont.setTextSize(MyUtils.sp2px(getContext(), 15));
mPaintFont.setAntiAlias(true);
for (TitleValueColorEntity e : data) {
float value = e.getValue();
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));
String title = e.getTitle();
float realx, realy;
// 依所處象限決定文字靠左或靠右,避免壓到扇形
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;
float gap = (value / sum < 0.2f) ? 10 : 5; // 小扇形多留一點間距
realy = (offsetY >= position.y) ? offsetY + gap : 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(percentage + "%", realx, realy + MyUtils.sp2px(getContext(), 30), mPaintFont);
}
}
}
// setData / getData 與各項 setter 略
}
package com.nekocode.xuedao.piechart;
public class TitleValueEntity {
private String title;
private float value;
public TitleValueEntity(String title, float value) { this.title = title; this.value = value; }
public TitleValueEntity() {}
// getter / setter 略
}
若要 coloured 版本,只需再派生一個 TitleValueColorEntity 加上 color 欄位即可。
幾個自繪的關鍵點:onDraw 中以寬高較小值推算半徑,可保證在任意版面下都是正圓;offset 從 -90 起算讓第一片從 12 點方向開始;文字位置以扇形中線的三角函數座標為基礎,再依左右象限調整對齊方式——這正是原庫容易錯位之處,把 quadrant 判斷補上之後就穩定了。若要支援動畫或點擊,可在 onTouchEvent 中反算角度落在哪一片,再呼叫 invalidate() 重繪。
更多 Android 相關資訊見 Android 專題頁面。