+ 3
How to draw a bar chart in Android? (no APIs)
Hi guys, I'm looking for a way to draw a bar chart in Android. I've tried with making custom views and with already included views, but I can't make them work as I need them to. My bars don't resize at the container's size. The bar should have this elements: https://ibb.co/GpPywFg Needed elements: Two joined bars like the ones in red to compare each bar. As the image, I need three pairs of bars (6 in general) Count of numbers (the ones in blue) The guides of colors from the top right (green ones) The optional elements (not necessary but would be nice to have) should be the orange and yellow ones. I need to make it without any libraries or external APIs.
1 Answer
0
To draw a bar chart in Android without using external libraries or APIs, you can create a custom View and override its onDraw method to manually draw the bars, labels, and other elements.
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Calculate dimensions and positions for bars, labels, and other elements based on data and container size.
// Draw bars
Paint barPaint = new Paint();
barPaint.setColor(Color.RED);
canvas.drawRect(leftBarRect, barPaint);
canvas.drawRect(rightBarRect, barPaint);
// Draw labels
Paint textPaint = new Paint();
textPaint.setColor(Color.BLUE);
textPaint.setTextSize(labelTextSize);
canvas.drawText("Label 1", label1X, labelY, textPaint);
// Repeat for other labels.
// Draw color guides
Paint guidePaint = new Paint();
guidePaint.setColor(Color.GREEN);
canvas.drawRect(guideRect, guidePaint);
// Draw optional elements (if needed)
Paint optionalPaint = new Paint();
optionalPaint.setColor(Color.YELLOW);
// Draw other optional elements.
// Repeat for other pairs of bars and elements.
// More drawing and calculations as needed...
}
This is a basic framework for drawing a bar chart. You will need to adapt it to your specific requirements, including the data source, dimensions, and other elements you want to include.