Rounded bars in ios Charts

2019-04-08 06:34发布

问题:

I've created a BarChart using BarChartView from ios-Charts but I can't figure out howto add rounded corners to bars.

This is the code that I'm using:

let barChart: BarChartView
//...
var xVals = [String]()
var yVals = [BarChartDataEntry]()
//...

let set1 = BarChartDataSet(yVals: yVals, label: "Label")

set1.drawValuesEnabled = false
set1.highlightLineWidth = 3
set1.colors = [UIColor.whiteColor()]

barChart.data = BarChartData(xVals: xVals, dataSet: set1)

I've looked for a property like set1.barCornerRadius to set, but I didn't find anything.

Here is what I have:

Here is what I need:

回答1:

In BarChartRenderer.swift you can to modify open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)

Then there's if-statement for stacked and nonstacked bars, choose your case and remove:

context.fill(barRect)

and instead of it add:

let bezierPath = UIBezierPath(roundedRect: barRect, cornerRadius: %YOUR_CORNER_RADIUS%)
context.addPath(bezierPath.cgPath)

context.drawPath(using: .fill)


回答2:

Seems that this feature is currently not supported but is under development. In the meanwhile take a look at this pull request.



回答3:

Rounded Bar chart using UIView:

let frame = CGRect(x: xPos, y: yPos, width: BAR_WIDTH_CONSTANT, height: barHeight)
let bar = UIView(frame: frame)
bar.layer.cornerRadius = BAR_WIDTH_CONSTANT < barHeight ? BAR_WIDTH_CONSTANT / 2 : barHeight / 2
bar.layer.masksToBounds = true
self.barView.addSubview(bar)

Here, BAR_WIDTH_CONSTANT is the width of each bar.



回答4:

If you don't want to wait for this pull request to be merged in the original library, there's a working solution that I use myself in a couple of projects.

This working example is based on all of the previous data I've collected all over the Internet. It works as of today but you have to do a few precautions before using it.

To make it work, all you have to do is replace the whole BarChartRenderer.swift file with this one.

First, have a backup copy of the original file. Then, make sure you replace the file every time you update your Charts CocoaPod, otherwise, the file will be overwritten.

In the end, to control the corner radius of your chart, just change the barCornerRadius = CGFloat(5.0) to whatever you want to.

Here's the final result I've got:

After you've replaced the file, make sure to clean your Xcode's build folder and then recompile your project for changes to take effect immediately.