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]
}
}
}
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.
cumulativeValue
- 0values[i]
- 50colors[i]
- redcumulativeValue
- 50values[i]
- 100colors[i]
- greencumulativeValue
- 150values[i]
- 150colors[i]
- redcumulativeValue
- 300values[i]
- 180colors[i]
- greenI 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: