MPAndroidChart: Change Shape of Bar Chart

不打扰是莪最后的温柔 提交于 2021-02-19 07:24:18

问题


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 corner of rectangle has radius about 4dp. i haven't found any method to draw that.


回答1:


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.



来源:https://stackoverflow.com/questions/53369115/mpandroidchart-change-shape-of-bar-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!