【问题标题】:How to get a string from a CGColor MacOS [closed]如何从 CGColor MacOS 中获取字符串 [关闭]
【发布时间】:2021-10-13 14:04:48
【问题描述】:

我正在尝试制作一个应用程序,以便更轻松地选择某些颜色,并且为了使用 NSPasteboard.setString 命令,我需要将颜色格式化为字符串。有没有办法可以将 CGColor 更改为字符串? 谢谢!

【问题讨论】:

标签: swift xcode macos colors


【解决方案1】:

这是我使用CGColor 做的一个有用的扩展。您可以获取 RGBA 组件,也可以将它们转换回来。

代码:

extension CGColor {
    /// Components of a color. Contains `rgba`.
    struct Components: Codable {
        let red: CGFloat
        let green: CGFloat
        let blue: CGFloat
        let alpha: CGFloat

        init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
            self.red = red
            self.green = green
            self.blue = blue
            self.alpha = alpha
        }

        init?(rgba: [CGFloat]) {
            guard rgba.count == 4 else { return nil }

            red = rgba[0]
            green = rgba[1]
            blue = rgba[2]
            alpha = rgba[3]
        }

        var all: [CGFloat] {
            [red, green, blue, alpha]
        }
    }

    var components: Components? {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        _ = NSColor(cgColor: self)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        let components = [red, green, blue, alpha]
        return Components(rgba: components)
    }

    static func create(from components: Components) -> CGColor {
        self.init(
            red: components.red,
            green: components.green,
            blue: components.blue,
            alpha: components.alpha
        )
    }
}

用法:

if let components = CGColor(red: 1, green: 0.2, blue: 0.2, alpha: 1).components {
    print(components)
    let new = CGColor.create(from: components)
    print(new)
}

打印:Components(red: 1.0, green: 0.2, blue: 0.2, alpha: 1.0)

打印:<CGColor 0x600003f1d500> [<CGColorSpace 0x600003f1ab80> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; Generic RGB Profile)] ( 1 0.2 0.2 1 )

【讨论】:

  • 嗯,我收到这些错误 = UIColor(cgColor: self).getRed(&red, green: &green, blue: &blue, alpha: &alpha) - 在范围内找不到 UIColor red: components.red, - 无法将“double”类型的值转换为预期的参数类型“CGFloat”
  • @TheAxolotlMan 我的错,现在应该修复!
  • 奇怪。我在red: components.red, green: components.green, blue: components.blue, alpha: components.alpha 上仍然遇到错误 - 无法将类型“Double”的值转换为预期的参数类型“CGFloat”。将“components.red”替换为“CGFloat(components.red)”
  • @TheAxolotlMan 啊,这可能是因为一个新的 Swift 特性,它被隐式转换了。我已将其更新为现在仅使用 CGFloat(我认为,至少 - 如果我错过任何内容,很难知道它何时是隐含的)
  • 酷,再次检查
猜你喜欢
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多