項目開發(fā)中我們需要通過 16 進制顏色字符串(比如:#F0FFFF)來初始化 UIColor庆捺,或者將 UIColor 轉(zhuǎn)成 16 進制字符串打印或顯示出來。下面是如何實現(xiàn)屁魏。
1.擴展 UIColor
為方便使用滔以,我們首先對 UIColor 進行擴展(UIColor+Ext.swift),增加相關(guān)的轉(zhuǎn)換方法和屬性
import UIKit
extension UIColor {
// Hex String -> UIColor
convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if hexString.hasPrefix("#") {
scanner.scanLocation = 1
}
var color: UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
// UIColor -> Hex String
var hexString: String? {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
let multiplier = CGFloat(255.999999)
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
return nil
}
if alpha == 1.0 {
return String(
format: "#%02lX%02lX%02lX",
Int(red * multiplier),
Int(green * multiplier),
Int(blue * multiplier)
)
}
else {
return String(
format: "#%02lX%02lX%02lX%02lX",
Int(red * multiplier),
Int(green * multiplier),
Int(blue * multiplier),
Int(alpha * multiplier)
)
}
}
}
2.使用方法
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 16進制顏色 -> UIColor
let color = UIColor(hexString: "#FFFFFF")
print("UIColor:", color)
// UIColor -> 16進制顏色
let hexString = color.hexString
print("16進制顏色值:", hexString ?? "")
}
}