給系統(tǒng)類 UIColor 添加分類。實現(xiàn)隨機顏色和字符串轉RGB功能。
隨機顏色
使用 extension
關鍵字給 UIColor 添加分類咏尝。在 {}
中創(chuàng)建 便利構造方法
莫瞬。
extension UIColor {
// add convenience initializer
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
}
}
添加類方法吨拗,實現(xiàn)顏色隨機爬范,RGB的隨機數(shù)使用 arc4random_uniform()
來生成捺檬。
// class function, random the color
class func randomColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
在這里预明,我創(chuàng)建了一個 UICollectionView 來展示每個 item 的背景顏色為隨機值役耕。
十六進制字符轉轉成 RGB
通過給定的十六進制的字符串采转,轉成對應的RGB值。需要對輸入的字符串進行位數(shù)判斷瞬痘,轉換成大寫故慈,然后分貝截取R、G框全、B對于的字符串察绷,使用 Scanner
類把字符串轉成數(shù)字。
// convert hexadecimal string to RGB value
convenience init?(hex: String, alpha: CGFloat = 1.0) {
// get the length of string
guard hex.characters.count >= 6 else {
return nil
}
// Convert to uppercased
var tempHex = hex.uppercased()
// prefix 0X/##/#
if tempHex.hasPrefix("0X") || tempHex.hasPrefix("##") {
tempHex = (tempHex as NSString).substring(from: 2)
}
if tempHex.hasPrefix("#") {
tempHex = (tempHex as NSString).substring(from: 1)
}
// cut the string津辩,get the R拆撼、G、B separately
var range = NSRange(location: 0, length: 2)
let rHex = (tempHex as NSString).substring(with: range)
range.location = 2
let gHex = (tempHex as NSString).substring(with: range)
range.location = 4
let bHex = (tempHex as NSString).substring(with: range)
// convert the hex string to number
var r: UInt32 = 0, g: UInt32 = 0, b: UInt32 = 0
// convert NSString object to number, pass an UInt32 type address
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))
}
使用時直接調用初始化方法:
view.backgroundColor = UIColor(hex: "0xFF26FF")
相關代碼: HLUIColorExtension