4

有谁知道是否可以从 Cocoa 中的 NSColor 获取颜色的十六进制值?

4

5 回答 5

9

使用蓝色 NSColor 的示例:

NSColor* color = [NSColor blueColor];

NSString* hexString = [NSString stringWithFormat:@"%02X%02X%02X", 
(int) (color.redComponent * 0xFF), (int) (color.greenComponent * 0xFF), 
(int) (color.blueComponent * 0xFF)];
于 2013-04-08T19:55:11.523 回答
4

我喜欢 DAH 的解决方案,我将其设为计算属性而不是函数:

import Cocoa

extension NSColor {

    var hexString: String {
        let red = Int(round(self.redComponent * 0xFF))
        let green = Int(round(self.greenComponent * 0xFF))
        let blue = Int(round(self.blueComponent * 0xFF))
        let hexString = NSString(format: "#%02X%02X%02X", red, green, blue)
        return hexString as String
    }

}
于 2015-09-02T05:09:15.540 回答
4

不会因色彩空间问题而崩溃的解决方案:

import Cocoa

extension NSColor {

    var hexString: String {
        guard let rgbColor = usingColorSpaceName(NSColorSpaceName.calibratedRGB) else {
            return "#FFFFFF"
        }
        let red = Int(round(rgbColor.redComponent * 0xFF))
        let green = Int(round(rgbColor.greenComponent * 0xFF))
        let blue = Int(round(rgbColor.blueComponent * 0xFF))
        let hexString = NSString(format: "#%02X%02X%02X", red, green, blue)
        return hexString as String
    }
}
于 2016-09-11T00:04:45.040 回答
2

一个选项是创建 NSColor 的扩展

public extension NSColor {
    func getHexString() -> String {
        let red = Int(round(self.redComponent * 0xFF))
        let grn = Int(round(self.greenComponent * 0xFF))
        let blu = Int(round(self.blueComponent * 0xFF))
        let hexString = NSString(format: "#%02X%02X%02X", red, grn, blu)
        return hexString
    }
}
于 2014-12-10T11:23:24.540 回答
0

为 Swift 4 更新

extension NSColor {

    var hexString: String {
        guard let rgbColor = usingColorSpaceName(NSColorSpaceName.calibratedRGB) else {
            return "FFFFFF"
        }
        let red = Int(round(rgbColor.redComponent * 0xFF))
        let green = Int(round(rgbColor.greenComponent * 0xFF))
        let blue = Int(round(rgbColor.blueComponent * 0xFF))
        let hexString = NSString(format: "#%02X%02X%02X", red, green, blue)
        return hexString as String
    }

}
于 2018-08-14T11:00:11.877 回答