Rotate value text vertically outside bar in BarChart MPAndroidChart
I am able to rotate the text but it is coming inside the bar which I have achieved using code below:
chart.setRenderer(CustomBarChartRenderer(context, this, this.getAnimator(), this.getViewPortHandler()))
public class CustomBarChartRenderer extends BarChartRenderer {
public CustomBarChartRenderer(BarDataProvider chart,
ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
@Override
public void drawValue(Canvas canvas, IValueFormatter formatter,
float value, Entry entry, int dataSetIndex, float x, float y, int color) {
mValuePaint.setColor(color);
canvas.save();
canvas.rotate(-90);
canvas.drawText(formatter.getFormattedValue(value, entry,
dataSetIndex, mViewPortHandler), x, y, mValuePaint);
canvas.restore();
}
}
Text is rotated but comes inside the bar can see in the image link below:

How to make text value properly align above the bar??
I was able to fix it by moving the label up.
Worth noticing is x and y dimensions changes internally as we are rotating the label so for moving label up you have to increase x value and not y value.
Also note to make it dynamic and work for all text lengths, I am calculating the pixel size for text to be displayed and moving label up by that pixel size only. See code below (in kotlin):
override fun drawValue(c: Canvas, formatter: IValueFormatter, value: Float, entry: Entry, dataSetIndex: Int, x: Float, y: Float, color: Int) {
mValuePaint.color = Color.WHITE
val text = formatter.getFormattedValue(value, entry, dataSetIndex, mViewPortHandler)
c.save()
val width = mValuePaint.measureText(text)
c.rotate(-90f, x, y)
c.drawText(text, x + (width / 2), y, mValuePaint)
c.restore()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With