如何在swift中将UIColor类型的值转换为Uint

时间:2016-04-03 12:43:46

标签: swift colors uicolor uint

我得到了这个UIColor:

UIColor(red: 0.2, green: 0.4118, blue: 0.1176, alpha: 1.0) 

我需要转换为Uint。我怎样才能做到这一点?

编辑:

func showEmailMessage(advice : String)
{
    _ = SCLAlertView().showSuccess("Congratulation", subTitle: advice, closeButtonTitle: "Ok", duration : 10, colorStyle: 0x33691e, colorTextButton: 0xFFFFFF)
}

颜色样式字段需要Uint

1 个答案:

答案 0 :(得分:5)

您可以使用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
}

有关详细信息,请参阅例如Language Guide - Advanced Operators,其中包含一些专门用于比特转换为RGB三元组的示例。