Android 使用Canvas繪製餅圖
阿新 • • 發佈:2019-02-15
效果:
嗯,一個很簡單的餅圖繪製。
用法
- 可以在xml檔案中配置,也可以直接new一個例項出來。
<com.paoword.oa.view.SectorGraphView
android:id="@+id/sector_graph"
android:layout_width="120dp"
android:layout_height="120dp" />
- 配置各區域的顏色和比例
mSectorGraph.setProportion(0.2f, 0.45f, 0.05f, 0.3f)
.setColor (Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW)
.draw();
setProportion()
和setColor()
的引數都是不定長引數,但是要注意兩個方法的引數個數要相同,不然就拋異常。
setProportion()
的引數為0~1的float型別,但是各引數值加到一起要等於1,否則畫出的餅圖就不準確
主程式碼
SectorGraphView.java
package com.paoword.oa.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by shichaohui on 16/1/16.
* <p>
* 餅圖
*/
public class SectorGraphView extends View {
private int[] colors;
private float[] proportions;
private Paint mPaint;
private Bitmap bitmap;
private Canvas mCanvas;
private RectF mRectf;
private int startAngle = -90, endAngle = 270;
private int[] colorStartAngles;
public SectorGraphView(Context context) {
super(context);
}
public SectorGraphView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SectorGraphView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SectorGraphView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
/**
* 設定餅圖每一塊的顏色
*
* @param color 顏色
*/
public SectorGraphView setColor(int... color) {
colors = color.clone();
return this;
}
/**
* 設定餅圖每一塊的比例
*
* @param proportion 比例(0-1)
*/
public SectorGraphView setProportion(float... proportion) {
proportions = proportion.clone();
return this;
}
/**
* 繪製餅圖
*/
public void draw() {
if (colors.length != proportions.length) {
throw new IllegalArgumentException("color和proportion的數量不同!");
} else {
post(() -> {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mRectf = new RectF(0, 0, getWidth(), getHeight());
colorStartAngles = new int[colors.length];
colorStartAngles[0] = startAngle;
for (int i = 1; i < colors.length; i++) {
colorStartAngles[i] = colorStartAngles[i - 1] + (int) (360 * proportions[i - 1]);
}
bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(bitmap);
logic();
});
}
}
private void logic() {
new Thread(() -> {
while (startAngle <= endAngle) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < colorStartAngles.length; i++) {
if (startAngle == colorStartAngles[i]) {
mPaint.setColor(colors[i]);
}
}
mCanvas.drawArc(mRectf, startAngle, 1, true, mPaint);
postInvalidate();
startAngle++;
}
}).start();
}
@Override
protected void onDraw(Canvas canvas) {
if (mPaint == null) return;
canvas.drawBitmap(bitmap, 0, 0, mPaint);
}
}