i\'m trying to develop a simple pie chart class for android. For now, it can take a map of labels and values and draw the pie chart. I\'m yet to add the legends for the pie,
There used to be another answer here that got deleted because it was a link only. The original link is here. The code is basically the same, but I took out the non text drawing portions and also scaled up the sizes to work better on modern screen densities.
This just shows a few things you can do with text drawing.
Here is the updated code:
public class MainActivity extends AppCompatActivity {
DemoView demoview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}
private class DemoView extends View {
public DemoView(Context context){
super(context);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// custom drawing code here
// remember: y increases from top to bottom
// x increases from left to right
int x = 0;
int y = 0;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
canvas.save();
canvas.translate(100, 200);
// make the entire canvas white
canvas.drawColor(Color.WHITE);
// draw some text using STROKE style
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.MAGENTA);
paint.setTextSize(100);
canvas.drawText("Style.STROKE", 0, 0, paint);
canvas.translate(0, 200);
// draw some text using FILL style
paint.setStyle(Paint.Style.FILL);
//turn antialiasing on
paint.setAntiAlias(true);
//paint.setTextSize(30);
canvas.drawText("Style.FILL", 0, 0, paint);
canvas.translate(0, 200);
// draw some rotated text
// get text width and height
// set desired drawing location
x = 75;
y = 185;
paint.setColor(Color.GRAY);
//paint.setTextSize(25);
String str2rotate = "Rotated!";
// draw bounding rect before rotating text
Rect rect = new Rect();
paint.getTextBounds(str2rotate, 0, str2rotate.length(), rect);
canvas.translate(x, y);
paint.setStyle(Paint.Style.FILL);
// draw unrotated text
canvas.drawText("!Rotated", 0, 0, paint);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRect(rect, paint);
// undo the translate
canvas.translate(-x, -y);
// rotate the canvas on center of the text to draw
canvas.rotate(-45, x + rect.exactCenterX(),
y + rect.exactCenterY());
// draw the rotated text
paint.setStyle(Paint.Style.FILL);
canvas.drawText(str2rotate, x, y, paint);
//undo the translation and rotation
canvas.restore();
}
}
}
Something else that I want to try later is drawing text along a path.
See also this fuller answer here that gives the following image.