这里我没有使用核心图形在 UIView 上获得替代颜色。 我想了解核心图形绘制。
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]
}
}
}
最佳答案
首先,您的代码中有一点错误。这些行可能应该颠倒过来:
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...
我们只需要在 for 循环的每次迭代开始时查看每个变量的值是什么。
- 第一次迭代
cumulativeValue
- 0值[i]
- 50colors[i]
- 红色- 所以这次迭代用红色填充矩形 (0, 0, 100, 50)
- 第二次迭代
cumulativeValue
- 50值[i]
- 100colors[i]
- 绿色- 所以这次迭代用绿色填充矩形 (0, 50, 100, 100)
- 第三次迭代
cumulativeValue
- 150值[i]
- 150colors[i]
- 红色- 所以这次迭代用红色填充矩形 (0, 150, 100, 150)
- 第四次迭代
cumulativeValue
- 300值[i]
- 180colors[i]
- 绿色- 所以这次迭代用绿色填充矩形 (0, 300, 100, 180)
我建议在一张纸上画出这些矩形,然后用颜色给它们着色。您将看到这是如何工作的。
简单解释一下,values
的每个元素存储了 View 每个“段”的长度。有 4 个部分,每个部分都比前一个长。而 cumulativeValue
存储下一段应该绘制的位置的 y 值。
这是它在 Playground 上的样子:
关于IOS 不在核心图形中显示替代颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49830693/