IOS 在 coregraphics 中不显示替代颜色
IOS not displaying alternative colours in coregraphics
这里我没有使用核心图形在 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]
}
}
}
调用前需要设置填充颜色fill()
。当我这样做时,它会按预期绘制颜色 Array
。
首先,您的代码中有一点错误。这些行可能应该颠倒过来:
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
values[i]
- 50
colors[i]
- 红色
- 所以这次迭代用红色填充矩形 (0, 0, 100, 50)
- 第二次迭代
cumulativeValue
- 50
values[i]
- 100
colors[i]
- 绿色
- 所以这次迭代用绿色填充矩形 (0, 50, 100, 100)
- 第三次迭代
cumulativeValue
- 150
values[i]
- 150
colors[i]
- 红色
- 所以这次迭代用红色填充矩形 (0, 150, 100, 150)
- 第四次迭代
cumulativeValue
- 300
values[i]
- 180
colors[i]
- 绿色
- 所以这次迭代用绿色填充矩形 (0, 300, 100, 180)
我建议在一张纸上画出这些矩形,然后用颜色给它们上色。您将看到这是如何工作的。
简单解释一下,values
的每个元素存储了每个"segment"视图的长度。有 4 个部分,每个部分都比前一个长。并且 cumulativeValue
存储下一段应绘制位置的 y 值。
这是它在操场上的样子:
这里我没有使用核心图形在 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]
}
}
}
调用前需要设置填充颜色fill()
。当我这样做时,它会按预期绘制颜色 Array
。
首先,您的代码中有一点错误。这些行可能应该颠倒过来:
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
- 0values[i]
- 50colors[i]
- 红色- 所以这次迭代用红色填充矩形 (0, 0, 100, 50)
- 第二次迭代
cumulativeValue
- 50values[i]
- 100colors[i]
- 绿色- 所以这次迭代用绿色填充矩形 (0, 50, 100, 100)
- 第三次迭代
cumulativeValue
- 150values[i]
- 150colors[i]
- 红色- 所以这次迭代用红色填充矩形 (0, 150, 100, 150)
- 第四次迭代
cumulativeValue
- 300values[i]
- 180colors[i]
- 绿色- 所以这次迭代用绿色填充矩形 (0, 300, 100, 180)
我建议在一张纸上画出这些矩形,然后用颜色给它们上色。您将看到这是如何工作的。
简单解释一下,values
的每个元素存储了每个"segment"视图的长度。有 4 个部分,每个部分都比前一个长。并且 cumulativeValue
存储下一段应绘制位置的 y 值。
这是它在操场上的样子: