有人知道在Cocoa中是否可以从NSColor获取颜色的十六进制值?
答案 0 :(得分:8)
使用蓝色NSColor的示例:
NSColor* color = [NSColor blueColor];
NSString* hexString = [NSString stringWithFormat:@"%02X%02X%02X",
(int) (color.redComponent * 0xFF), (int) (color.greenComponent * 0xFF),
(int) (color.blueComponent * 0xFF)];
答案 1 :(得分: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
}
}
答案 2 :(得分:3)
我喜欢D.A.H的解决方案,我把它作为计算属性而不是函数:
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
}
}
答案 3 :(得分: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
}
}
答案 4 :(得分: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
}
}