IOS 不在核心图形中显示替代颜色

标签 ios swift xcode core-graphics

这里我没有使用核心图形在 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] - 50
    • colors[i] - 红色
    • 所以这次迭代用红色填充矩形 (0, 0, 100, 50)
  • 第二次迭代
    • cumulativeValue - 50
    • 值[i] - 100
    • colors[i] - 绿色
    • 所以这次迭代用绿色填充矩形 (0, 50, 100, 100)
  • 第三次迭代
    • cumulativeValue - 150
    • 值[i] - 150
    • colors[i] - 红色
    • 所以这次迭代用红色填充矩形 (0, 150, 100, 150)
  • 第四次迭代
    • cumulativeValue - 300
    • 值[i] - 180
    • colors[i] - 绿色
    • 所以这次迭代用绿色填充矩形 (0, 300, 100, 180)

我建议在一张纸上画出这些矩形,然后用颜色给它们着色。您将看到这是如何工作的。

简单解释一下,values的每个元素存储了 View 每个“段”的长度。有 4 个部分,每个部分都比前一个长。而 cumulativeValue 存储下一段应该绘制的位置的 y 值。

这是它在 Playground 上的样子:

enter image description here

关于IOS 不在核心图形中显示替代颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49830693/

相关文章:

iphone - 跟踪 UIView 帧变化动画

iphone - 如何在滚动 uiscrollview 时更改图像背景?

json - 单击 Tableview 单元格不显示数据

ios - Parse 中的 UITableView,索引不正确

ios - FBSOpenApplicationErrorDomain 错误 1

ios - 如何使安装了 CocoaPods 的 pod 可用于我工作区中的所有项目?

ios - Ad hoc .ipa 未使用 iTune 安装

objective-c - iOS:NSString变量返回null

ios - 如何从Observable <BleHandler.BlePeripheral>到BleHandler.BlePeripheral?

iphone - 如何在 xcode 4.3 lion 中查找将调用函数而不是搜索工具的位置