Search code examples
iosswiftxcodecore-graphics

IOS not displaying alternative colours in coregraphics


Here I am not getting alternative colors on the UIView using core graphics. I would like to understand core graphics drawing.

    class ProgressMenuView: UIView {

    var colors : [UIColor] = [UIColor.red, UIColor.green,UIColor.red,UIColor.green]
    var values : [CGFloat] = [50, 100, 150, 180]

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        let ctx = UIGraphicsGetCurrentContext()

        var cumulativeValue:CGFloat = 0

        for i in 0..<self.values.count {
            ctx!.fill(CGRect(x: 0, y: cumulativeValue, width:100, height: values[i]))
            ctx!.setFillColor(colors[i].cgColor)
            cumulativeValue += values[i]
        }

    }

}

Solution

  • First, there is a little error in your code. These lines should probably be reversed:

    ctx!.fill(CGRect(x: 0, y: cumulativeValue, width:100, height: values[i])) // ...then fill
    ctx!.setFillColor(colors[i].cgColor) // you should first set the color...
    

    We just need to look at what each variable's value is at the start of each iteration of the for loop.

    • 1st iteration
      • cumulativeValue - 0
      • values[i] - 50
      • colors[i] - red
      • so this iteration fills the rect (0, 0, 100, 50) with red
    • 2nd iteration
      • cumulativeValue - 50
      • values[i] - 100
      • colors[i] - green
      • so this iteration fills the rect (0, 50, 100, 100) with green
    • 3rd iteration
      • cumulativeValue - 150
      • values[i] - 150
      • colors[i] - red
      • so this iteration fills the rect (0, 150, 100, 150) with red
    • 4th iteration
      • cumulativeValue - 300
      • values[i] - 180
      • colors[i] - green
      • so this iteration fills the rect (0, 300, 100, 180) with green

    I recommend drawing these rects on a piece of paper and colouring them in with the colors. You will see how this works.

    To explain briefly, each element of values stores the length of each "segment" of the view. There are 4 segments, each longer than the previous one. And cumulativeValue stores the y value of where the next segment should be drawn.

    Here's how it looks in a playground:

    enter image description here