2

I want to use iOS-Charts with Swift to draw some line charts to show the data. Now, I have a requirement that put a small icon beside each point.

enter image description here

Now I can add UIImage on the graph, but the problem is how can I get the CGPoint coordinates of each points correctly.

If I change the orientation of device or device type, the position of images are still fixed, not change correspondingly. Here is iPhone 6s picture.

enter image description here

Here is my current code:

for i in 0..<dataPoints.count {
        let pointLeft = lineChartView.getPosition(dataEntries[i], axis: .Left)

        let image = UIImage(named: numbers[i])
        let imageView = UIImageView(image:image!)
        imageView.frame = CGRect(x: pointLeft.x, y: pointLeft.y, width: 16, height: 16)
        lineChartView.addSubview(imageView)

    }
Leo
  • 303
  • 1
  • 4
  • 13

1 Answers1

5

You can modify private func drawCircles(context context: CGContext) inside LineChartRenderer.swift to do the following: inside the loop where the circles are drawing use pt var which is calculated there and add something like this:

let image = UIImage(named: numbers[i])
image?.drawInRect(CGRect(x: pt.x, y: pt.y, width: 16, height: 16))

Obviously, you need to play with CGRect to place images the way you need. This method will be called every time device orientation will be changing etc.

keyv
  • 2,430
  • 1
  • 18
  • 15
  • 2
    You can actually extend from LineChartRenderer and override drawExtras(CGContext). This is because drawCircles(CGContext) is declared as fileprivate. Once you have your LineChartView, you can assign your newly extended LineChartRenderer with NewChartRenderer(dataProvider: lineChartView, animator: lineChartView.chartAnimator, viewPortHandler: lineChartView.viewPortHandler). lineChartView is just an IBOutlet of type LineChartView!. This, in my opinion, is a lot cleaner than modifying the original code. – Takeshi Kaga Dec 06 '16 at 01:24