Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPAndroidChart: Change Shape of Bar Chart

Tags:

android

kotlin

i already read answers of question that similar to mine. but, i don't understand and i think that's so complex. maybe some of you have a trick how to make it simple. i am using 'com.github.PhilJay:MPAndroidChart:v2.2.4' library, btw. i want to make a bar chart style like this picture.

the bar chart

the corner of rectangle has radius about 4dp. i haven't found any method to draw that.

like image 963
Mavisa9 Avatar asked Nov 08 '22 00:11

Mavisa9


1 Answers

Looks like there is no way to make it simple. Finally I came up with a clumsy, but working solution which worked well in my case. First subclass the BarChartRenderer and set it to your chart:

class CustomBarRenderer constructor(
         chart: BarChart, 
         animator: ChartAnimator, 
         vpHandler: ViewPortHandler,
         cornerDimens: Float
) : BarChartRenderer(chart, animator, vpHandler)

//...
chart.renderer = CustomBarRenderer(chart, chart.animator, chart.viewPortHandler, cornersDimens)
//...

BarChartRenderer inherits mRenderPaint member which is used to draw bar lines, so if you need some slight modification (bar border width, fill type or anything else) you can simply override mRendererPaint in your init block and you're good to go.

init {
    mRendererPaint = Paint().also {
        // all paint properties you need
    }
}

But this is not enough to get that rounded corners bars. The reason is that renderer draws them using canvas.drawRect inside drawDataSet method, so we need to go deeper and override it and change this invocation to canvas.drawRoundRect:

override fun drawDataSet(c: Canvas, dataSet: IBarDataSet, index: Int) {

    //....
    c.drawRoundRect(
         buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],
         buffer.buffer[j + 3], cornersDimen, cornersDimen, mRenderPaint
    )
    //....
}

Important - although the majority of renderer's members are protected and easy to use or override, there are still some private stuff which is used for drawing shadows. Unfortunately I had to just remove shadows rendering (in first place just because I didn't need them), so for somebody this could be an incomplete solution.

like image 165
Viacheslav Avatar answered Nov 14 '22 21:11

Viacheslav