編輯:關於 Android 程式設計
這篇示範怎麼用 Canvas 手繪一張圓餅統計圖,重點是標籤、引線、百分比全部依扇區大小自動排布,不需要手動調座標。
先看成果:

特點:
1. 使用方式很直覺,先在 XML 裡擺上這個 View,程式碼中餵資料即可:
PieChartView pieChartView = (PieChartView) findViewById(R.id.pie_chart); PieChartView.PieItemBean[] items = new PieChartView.PieItemBean[]{ new PieChartView.PieItemBean("娛樂", 200), new PieChartView.PieItemBean("旅行", 100), new PieChartView.PieItemBean("學習", 120), new PieChartView.PieItemBean("人際關系", 160), new PieChartView.PieItemBean("交通", 100), new PieChartView.PieItemBean("餐飲", 480) }; pieChartView.setPieItems(items);
2. 項目數量、大小、引線位置與長度全部自適應:左半邊的項目往左拉線、右半邊往右拉線,文字與百分比居中對齊,底線長度隨文字寬度伸縮。遇到特別小的扇區,會自動把引線拉長,盡量避開文字互相遮壓。
核心程式碼 PieChartView.java:
public class PieChartView extends View { private int screenW, screenH; /** * The paint to draw text, pie and line. */ private Paint textPaint, piePaint, linePaint; /** * The center and the radius of the pie. */ private int pieCenterX, pieCenterY, pieRadius; /** * The oval to draw the oval in. */ private RectF pieOval; private float smallMargin; private int[] mPieColors = new int[]{Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.MAGENTA, Color.CYAN}; private PieItemBean[] mPieItems; private float totalValue; public PieChartView(Context context) { super(context); init(context); } public PieChartView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PieChartView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { //init screen screenW = ScreenUtils.getScreenW(context); screenH = ScreenUtils.getScreenH(context); pieCenterX = screenW / 2; pieCenterY = screenH / 3; pieRadius = screenW / 4; smallMargin = ScreenUtils.dp2px(context, 5); pieOval = new RectF(); pieOval.left = pieCenterX - pieRadius; pieOval.top = pieCenterY - pieRadius; pieOval.right = pieCenterX + pieRadius; pieOval.bottom = pieCenterY + pieRadius; //The paint to draw text. textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setTextSize(ScreenUtils.dp2px(context, 16)); //The paint to draw circle. piePaint = new Paint(); piePaint.setAntiAlias(true); piePaint.setStyle(Paint.Style.FILL); //The paint to draw line to show the concrete text linePaint = new Paint(); linePaint.setAntiAlias(true); linePaint.setStrokeWidth(ScreenUtils.dp2px(context, 1)); } //The degree position of the last item arc's center. private float lastDegree = 0; //The count of the continues 'small' item. private int addTimes = 0; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPieItems != null && mPieItems.length > 0) { float start = 0.0f; for (int i = 0; i < mPieItems.length; i++) { //draw pie piePaint.setColor(mPieColors[i % mPieColors.length]); float sweep = mPieItems[i].getItemValue() / totalValue * 360; canvas.drawArc(pieOval, start, sweep, true, piePaint); //draw line away from the pie float radians = (float) ((start + sweep / 2) / 180 * Math.PI); float lineStartX = pieCenterX + pieRadius * 0.7f * (float) (Math.cos(radians)); float lineStartY = pieCenterY + pieRadius * 0.7f * (float) (Math.sin(radians)); float lineStopX, lineStopY; float rate; if (getOffset(start + sweep / 2) > 60) { rate = 1.3f; } else if (getOffset(start + sweep / 2) > 30) { rate = 1.2f; } else { rate = 1.1f; } //If the item is very small, make the text further away from the pie to avoid being hided by other text. if (start + sweep / 2 - lastDegree < 30) { addTimes++; rate += 0.2f * addTimes; } else { addTimes = 0; } lineStopX = pieCenterX + pieRadius * rate * (float) (Math.cos(radians)); lineStopY = pieCenterY + pieRadius * rate * (float) (Math.sin(radians)); canvas.drawLine(lineStartX, lineStartY, lineStopX, lineStopY, linePaint); //write text String itemTypeText = mPieItems[i].getItemType(); String itemPercentText = Utility.formatFloat(mPieItems[i].getItemValue() / totalValue * 100) + "%"; float itemTypeTextLen = textPaint.measureText(itemTypeText); float itemPercentTextLen = textPaint.measureText(itemPercentText); float lineTextWidth = Math.max(itemTypeTextLen, itemPercentTextLen); float textStartX = lineStopX; float textStartY = lineStopY - smallMargin; float percentStartX = lineStopX; float percentStartY = lineStopY + textPaint.getTextSize(); if (lineStartX > pieCenterX) { textStartX += (smallMargin + Math.abs(itemTypeTextLen - lineTextWidth) / 2); percentStartX += (smallMargin + Math.abs(itemPercentTextLen - lineTextWidth) / 2); } else { textStartX -= (smallMargin + lineTextWidth - Math.abs(itemTypeTextLen - lineTextWidth) / 2); percentStartX -= (smallMargin + lineTextWidth - Math.abs(itemPercentTextLen - lineTextWidth) / 2); } canvas.drawText(itemTypeText, textStartX, textStartY, textPaint); //draw percent text canvas.drawText(itemPercentText, percentStartX, percentStartY, textPaint); //draw text underline float textLineStopX = lineStopX; if (lineStartX > pieCenterX) { textLineStopX += (lineTextWidth + smallMargin * 2); } else { textLineStopX -= (lineTextWidth + smallMargin * 2); } canvas.drawLine(lineStopX, lineStopY, textLineStopX, lineStopY, linePaint); lastDegree = start + sweep / 2; start += sweep; } } } public PieItemBean[] getPieItems() { return mPieItems; } public void setPieItems(PieItemBean[] pieItems) { this.mPieItems = pieItems; totalValue = 0; for (PieItemBean item : mPieItems) { totalValue += item.getItemValue(); } invalidate(); } private float getOffset(float radius) { int a = (int) (radius % 360 / 90); switch (a) { case 0: return radius; case 1: return 180 - radius; case 2: return radius - 180; case 3: return 360 - radius; } return radius; } static class PieItemBean { private String itemType; private float itemValue; PieItemBean(String itemType, float itemValue) { this.itemType = itemType; this.itemValue = itemValue; } public String getItemType() { return itemType; } public void setItemType(String itemType) { this.itemType = itemType; } public float getItemValue() { return itemValue; } public void setItemValue(float itemValue) { this.itemValue = itemValue; } } }
幾個值得留意的設計:getOffset() 把角度折算到 0~90 的範圍,用來判斷扇區落在哪個象限,進而決定引線要往外伸多遠;lastDegree 與 addTimes 的搭配則處理連續小扇區的堆疊問題,避免標籤疊成一團。
完整實例程式碼可至本站下載。
更多關於 Android 相關內容有興趣的讀者可查看本站專題:《Android圖形與圖像處理技巧總結》、《Android開發入門與進階教程》、《Android調試技巧與常見問題解決方法匯總》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》
Android 字母索引(側邊欄)的完整實現
剛學 Android 時就想自己手寫一個索引,但當時還是菜鳥,一直沒動手。昨天終於寫了一個,今天貼出來備用。先看效果圖: 由於列表是我自己封裝的,看到展示頁面時可能會
Android 自定義控件基本原理詳解(一):從 Measure、Layout 到 Draw
前言:在日常的 Android 開發中,我們會頻繁地和各種控件打交道。然而,Android 原生提供的控件未必都能滿足業務需求,這時候就得靠我們自己動手實作自定義控件了。
Activity 入門實踐:從第一個按鈕到選單的完整流程
照著《第一行代碼 Android》的脈絡走一遍 Activity 的基本用法,過程有點像當年敲 Java 的 Hello World——步驟簡單,但幾個容易踩的小坑值得記
GreenDAO 入門:Android 輕量快速的 ORM 解決方案
Android 自帶的 SQLite,大家一定都用過。然而在使用的過程中,我們往往需要做許多額外的工作,比如編寫 SQL 語句、解析查詢結果等。於是,適用於 Androi