Cees
Cees

Reputation: 424

Making a very simple graph with uibezierpath

my question was

I want to create a simple line graph with certain values. This is done in a view within the mainviewcontroller. I created a UIview named chart. I pass the data to the chart when its retrieved from the API. I figured out how to draw the axis but I am stuck now. I cant find anything on google on how to set labels on intervals and to make the points appear dynamically.

  • draw the xasis and its labels.
  • draw the dots in the graph.

My salution

  • i figured out how to do all the things i asked for.

The code I have now:

class ChartView: UIView {

//some variables
var times: [String] = []
var AmountOfRain: [Double] = []
let pathy = UIBezierPath()
let pathx = UIBezierPath()
var beginwitharray = Array<CGFloat>()

// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    // Drawing code

    //draw the y line
    pathy.move(to: CGPoint(x: 30, y: 10))
    pathy.addLine(to: CGPoint(x: 30, y: 10))
    pathy.addLine(to: CGPoint(x: 30, y: frame.size.height - 30))
    UIColor.black.setStroke()
    pathy.lineWidth = 1.0
    pathy.stroke()

    //draw the x line
    pathx.move(to: CGPoint(x: 30, y: frame.size.height - 30))
    pathx.addLine(to: CGPoint(x: 30, y: frame.size.height - 30))
    pathx.addLine(to: CGPoint(x: frame.size.width - 30, y: frame.size.height - 30))
    UIColor.black.setStroke()
    pathx.lineWidth = 1.0
    pathx.stroke()

    //when the data arrives form the SUPER slow duienradar API refresh it with the data
    if beginwitharray != []{
        //remove the label retriving data
        let label = viewWithTag(1)
        DispatchQueue.main.sync {
            label?.removeFromSuperview()
        }
        //create the dots in the graph
        var point = CGPoint()
        //simple way to do 2 loop in 1 loop.
        var intforbeginarray = 0
        let stoke = UIBezierPath()
        //get the first 6 itmes out of the rain array cuz of space issues
        let first6aumountarray = AmountOfRain[0...5]
        stoke.move(to: CGPoint(x: 30, y: self.frame.size.height - 30))

        //loop trough the data in the amounts array
        for amount in first6aumountarray{
            //determen the hight of the dot
            let InitialHeight = (CGFloat(amount) * (self.frame.size.height - 30))/6
            let pointHeight = (frame.size.height - 30) - InitialHeight

                //make the point so we can draw it using UIbezierpath()
                point = CGPoint(x: beginwitharray[intforbeginarray] + 20, y: pointHeight)
                intforbeginarray += 1

                //create the dot
                let dot = UIBezierPath()
                dot.addArc(withCenter: point, radius: CGFloat(5), startAngle: CGFloat(0), endAngle: CGFloat(360), clockwise: true)
                UIColor.black.setFill()
                dot.lineWidth = 30
                dot.fill()

                //create the line between dots will give a warning on the last one cuz the last one doenst go anyway
                stoke.addLine(to: point)
                stoke.move(to: point)
                stoke.lineWidth = 1
                UIColor.black.setStroke()
        }
        //make the strokes
        stoke.stroke()
    }
}
func getvalues(RainData: [Double], TimesData:[String]){

    //assing the data to the subview
    self.AmountOfRain = RainData
    self.times = TimesData

    //xaxis values
    let maxint = [0, 1, 2, 3, 4, 5, 6]

    //calculate the hight spacing to fit the graph
    let heightperstep = ((self.frame.size.height - 5)/6)-5
    var beginheight = self.frame.size.height - 35

    //calculate the width spacing to fit the graph
    let widthperstep = ((self.frame.size.width - 5)/6)-5
    var beginwith = CGFloat(30)

    //extra check to see if we have data at all.
    if times != []{
        //get the first 6 items out of the times array for use in our graph
        let first6 = times[0...5]
        //draw the label on the main queue
        DispatchQueue.main.sync {
            //draw the xaxis labels accroding to the spacing
            for number in maxint{
                let label = UILabel(frame: CGRect(x: 5, y: beginheight, width: 25, height: 15))
                label.text = "\(number)"
                self.addSubview(label)
                beginheight = beginheight - heightperstep
            }
            //draw the yaxis labels according to the spacing
            for time in first6{
                let label = UILabel(frame: CGRect(x: beginwith, y: self.frame.size.height - 20, width: 55, height: 15))
                label.text = time
                self.addSubview(label)
                beginwitharray.append(beginwith)
                beginwith = beginwith + widthperstep
            }
        }
    }
    //redrawthe graph with new data.
    setNeedsDisplay()
}}

Any help would be appreciated. I also can't use a lib or a pod since this is a school project and I need to create a simple graph.

EDIT:

Completed my code, cleared up an error when running this code

What I did first was to draw the x-asis and the y-axis. After this I considered reasonable values for the aumountofrain data. this turns out cannot really be higher then 6. Since I could fit around 6 labels in the space I have the steps where easy go down by 1 till I hit 0. The calculations I did are for my specific frame height. After I figured it all out and the padding for the y-asxis. It was a matter of figuring out how to get the dots in the right place. Since I already have the data in the beginwitharray I just needed to calculate the height. Then it was simply loop trough the data and draw each dot. Then I just had to connect the dots using the uibezierpath.

i hope my troubles will save someone a lot of time when they read how i done it.

Upvotes: 1

Views: 1179

Answers (1)

Aaron Halvorsen
Aaron Halvorsen

Reputation: 2680

This might be helpful: Draw Graph curves with UIBezierPath

Essentially what you need to do is for every data set you have you need to know the y-axis range of values and based on those ranges assign each value a CGFloat value (in your case inches of rain needs to correlate to a certain CGFloat value). Let's say you have your set amountOfRain = [0.1, 1.3, 1.5, 0.9, 0.1, 0] so your range is var rangeY = amountOfRain.max() - amountOfRain.min(). now lets find out where your first data point 0.1 should go on your graph by converting inches of rain to a CGFloat value that corresponds to the axis you've drawn already, this equation is just basic algebra: let y1 = (amountOfRain[0]/rangeY)*((frame.size.height-30) - 10) + 10 now it looks like your rain samples are at regular intervals so maybe let x1:CGFloat = 10 now you can add a dot or something at the CGPoint corresponding with (x1,y1). If you did this with all the data points it would create a graph that has your maximum value at the top of the graph and minimum value at the bottom. Good Luck!

Upvotes: 2

Related Questions