如何在此UIColor扩展中包含alpha?
extension UIColor {
convenience init(hex:Int) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff)
}
}
答案 0 :(得分:1)
首先,UIColor
没有任何带整数的初始值设定项。我假设你有另一个类似于this的扩展名。您必须添加对alpha的支持
// we cannot name the param "alpha" because of a name collision
convenience init(red: Int, green: Int, blue: Int, a: Int = 255) {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(a) / 255)
}
convenience init(hex:Int) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff, a:(hex >> 24) & 0xff)
}
(假设alpha是第一个组件)。
如果您希望alpha只是一个额外的十进制数
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(hex:Int, a: CGFloat = 1.0) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff, a: a)
}