您可以使用该UIColor.getRed(...)
方法将颜色提取为CGFloat
,然后将三元组的值转换为变量CGFloat
的正确位位置。UInt32
// Example: use color triplet CC6699 "=" {204, 102, 153} (RGB triplet)
let color = UIColor(red: 204.0/255.0, green: 102.0/255.0, blue: 153.0/255.0, alpha: 1.0)
// read colors to CGFloats and convert and position to proper bit positions in UInt32
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
var colorAsUInt : UInt32 = 0
colorAsUInt += UInt32(red * 255.0) << 16 +
UInt32(green * 255.0) << 8 +
UInt32(blue * 255.0)
colorAsUInt == 0xCC6699 // true
}
有关详细信息,请参阅例如语言指南 - 高级运算符,其中包含除其他有价值的内容外,还包含一个专门针对 RGB 三元组进行位移的示例。