Created
November 27, 2015 20:21
-
-
Save ElFeesho/f42a56c48b88f4ac0c2c to your computer and use it in GitHub Desktop.
Simple line only Pie chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.content.Context; | |
| import android.graphics.Canvas; | |
| import android.graphics.Paint; | |
| import android.graphics.RectF; | |
| import android.util.AttributeSet; | |
| import android.view.View; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| public class PieChartView extends View { | |
| private RectF bounds; | |
| private Paint paint = new Paint(); | |
| public static class Data | |
| { | |
| public final float value; | |
| public final int colour; | |
| public Data(float value, int colour) { | |
| this.value = value; | |
| this.colour = colour; | |
| } | |
| } | |
| private final List<Data> dataPoints = new ArrayList<>(); | |
| public PieChartView(Context context) { | |
| this(context, null, 0); | |
| } | |
| public PieChartView(Context context, AttributeSet attrs) { | |
| this(context, attrs, 0); | |
| } | |
| public PieChartView(Context context, AttributeSet attrs, int defStyleAttr) { | |
| super(context, attrs, defStyleAttr); | |
| paint.setStrokeWidth(2); | |
| paint.setStyle(Paint.Style.STROKE); | |
| if (isInEditMode()) | |
| { | |
| addData(new Data(10, 0xffff0000)); | |
| addData(new Data(20, 0xff00ff00)); | |
| } | |
| } | |
| @Override | |
| protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
| setMeasuredDimension(widthMeasureSpec, widthMeasureSpec); | |
| } | |
| @Override | |
| protected void onSizeChanged(int w, int h, int oldw, int oldh) { | |
| super.onSizeChanged(w, h, oldw, oldh); | |
| bounds = new RectF(3, 3, w-6, h-6); | |
| } | |
| @Override | |
| protected void onDraw(Canvas canvas) { | |
| super.onDraw(canvas); | |
| float lastStartAngle = 0; | |
| float totalData = determineTotalData(); | |
| for (Data dataPoint : dataPoints) { | |
| float sweep = (dataPoint.value / totalData) * 360; | |
| paint.setColor(dataPoint.colour); | |
| canvas.drawArc(bounds, lastStartAngle, sweep, false, paint); | |
| lastStartAngle += sweep; | |
| } | |
| } | |
| public void addData(Data data) | |
| { | |
| dataPoints.add(data); | |
| postInvalidate(); | |
| } | |
| private float determineTotalData() | |
| { | |
| float total = 0; | |
| for (Data dataPoint : dataPoints) { | |
| total += dataPoint.value; | |
| } | |
| return total; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment