这就是我想要的(从黄色一直到顶部,颜色应该是红色):
现在我可以创建UIView并填充块,但是我很难在每个块中淡入正确的颜色。这可以复制粘贴到游乐场:
import UIKit
class Divider: UIView{
var blocks: CGFloat = 10
override func draw(_ rect: CGRect) {
let spaceBetween = frame.height / blocks
for i in 0...Int(blocks) - 2{
let bezierPath = UIBezierPath()
UIColor.blue.setStroke()
bezierPath.lineWidth = 1
bezierPath.move(to: CGPoint(x: 0, y: spaceBetween + spaceBetween * CGFloat(i)))
bezierPath.addLine(to: CGPoint(x: frame.width, y: spaceBetween + spaceBetween * CGFloat(i)))
bezierPath.stroke()
}
}
func fill(level: Int){
let start = 255/blocks * (blocks - CGFloat(level - 1))
//I am confused on the endColor and beginColor
let endColor = UIColor(red: start/255, green: start/255, blue: 0, alpha: 1).cgColor
let beginColor = UIColor(red: start/255, green: start/255, blue: 0, alpha: 1).cgColor
let spaceBetween = frame.height / (blocks)
let layer = CAGradientLayer()
layer.frame = CGRect(x: 0, y: frame.height - (spaceBetween * CGFloat(level)), width: frame.width, height: spaceBetween)
layer.colors = [endColor, beginColor]
layer.locations = [0.0, 1.0]
self.layer.addSublayer(layer)
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = .green
}
}
let view = Divider(frame: CGRect(x: 0, y: 0, width: 50, height: 100))
view.fill(level: 1)
view.fill(level: 2)
view.fill(level: 3)
view.fill(level: 4)
如何确保顶部块是红色的,底部块是黄色的,并且它之间的所有内容都很好地消失了?