iOS 开发对于方法的拓展实在不行,不像 android 可以直接加载十六进制色值UIColor(argb: 0xFFFFFFFF)CV我们知道
#ffffff实际上是用十六进制来表示3种颜色,也就是:红色ff,绿色ff和蓝色ff。所以你可以使用0x前缀的十六进制表示法,来设置UIColor,例如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透明度? 我们一般使用UIColor.withAlphaComponent来设置颜色的透明度,例如let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)
withAlphaComponent() 来设置颜色的透明度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,因为这回与现有构造方法名称发生冲突,所以就用缩写字母a来表示
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)GitHub 新建了一个仓库,正在为大家整理 iOS 学习笔记,欢迎大家 star 支持:https://github.com/Knowledge-Precipitation-Tribe/ios_notes