Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a Marker on ios-charts?

I'm creating an iOS app using Objective-C and I need to use ios-charts.

Now I'm facing a problem that I couldn't find the way to add a Marker to my graphView.

Also, I need to change the YAxis data set by user action, but I have no idea how to implement this feature.

Thank you for your help.

like image 741
Masaru Kitajima Avatar asked Nov 29 '22 01:11

Masaru Kitajima


1 Answers

Unfortunately in the library itself there is no class that displays a marker with text. There is this BalloonMarker class in the examples provided on github but it is not included in the library. So you can use that BalloonMarker from the examples on github or alternatively below is another simple marker class that you can use instead. I think it might be easier to understand and customize than the BallonMarker:

class ChartMarker: MarkerView {
    var text = ""

    override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
        super.refreshContent(entry: entry, highlight: highlight)
        text = String(entry.y)
    }

    override func draw(context: CGContext, point: CGPoint) {
        super.draw(context: context, point: point)

        var drawAttributes = [NSAttributedStringKey : Any]()
        drawAttributes[.font] = UIFont.systemFont(ofSize: 15)
        drawAttributes[.foregroundColor] = UIColor.white
        drawAttributes[.backgroundColor] = UIColor.darkGray

        self.bounds.size = (" \(text) " as NSString).size(withAttributes: drawAttributes)
        self.offset = CGPoint(x: 0, y: -self.bounds.size.height - 2)

        let offset = self.offsetForDrawing(atPoint: point)

        drawText(text: " \(text) " as NSString, rect: CGRect(origin: CGPoint(x: point.x + offset.x, y: point.y + offset.y), size: self.bounds.size), withAttributes: drawAttributes)
    }

    func drawText(text: NSString, rect: CGRect, withAttributes attributes: [NSAttributedStringKey : Any]? = nil) {
        let size = text.size(withAttributes: attributes)
        let centeredRect = CGRect(x: rect.origin.x + (rect.size.width - size.width) / 2.0, y: rect.origin.y + (rect.size.height - size.height) / 2.0, width: size.width, height: size.height)
        text.draw(in: centeredRect, withAttributes: attributes)
    }
}

and to use it with given chart:

let marker = ChartMarker()
marker.chartView = chartView
chartView.marker = marker
like image 91
Leszek Szary Avatar answered Dec 15 '22 15:12

Leszek Szary