大话西游666
#ffffff实际上是三种颜色组成的十六进制表示法-红色。ff绿ff蓝色ff..您可以使用SWIFT编写十六进制表示法0x前缀,例如0xFF为了简化转换,让我们创建一个接受整数(0-255)值的初始化器:extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}}用法:let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)let color2 = UIColor(rgb: 0xFFFFFF)怎么得到阿尔法?根据用例的不同,您可以简单地使用本机UIColor.withAlphaComponent方法,如:let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)也可以向上述方法添加附加(可选)参数:convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: a )}convenience init(rgb: Int, a: CGFloat = 1.0) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF,
a: a )}(我们不能命名参数alpha因为名称与现有的初始化程序发生冲突)。称为:let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)要将alpha作为整数0-255,我们可以convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: CGFloat(a) / 255.0
)}// let's suppose alpha is the first component (ARGB)convenience init(argb: Int) {
self.init(
red: (argb >> 16) & 0xFF,
green: (argb >> 8) & 0xFF,
blue: argb & 0xFF,
a: (argb >> 24) & 0xFF
)}被称为let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)let color2 = UIColor(argb: 0xFFFFFFFF)或者是前几种方法的组合。绝对没有必要使用字符串。