可以通過以下兩種方式轉(zhuǎn)換,原理都是一樣的挤忙,只是使用方式不一樣。
給 String
添加擴(kuò)展
extension String {
func uicolor(alpha: CGFloat = 1.0) -> UIColor {
// 存儲(chǔ)轉(zhuǎn)換后的數(shù)值
var red: UInt32 = 0, green: UInt32 = 0, blue: UInt32 = 0
var hex = self
// 如果傳入的十六進(jìn)制顏色有前綴谈喳,去掉前綴
if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2))
} else if hex.hasPrefix("#") {
hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1))
}
// 如果傳入的字符數(shù)量不足6位按照后邊都為0處理册烈,當(dāng)然你也可以進(jìn)行其它操作
if characters.count < 6 {
for _ in 0..<6-characters.count {
hex += "0"
}
}
// 分別進(jìn)行轉(zhuǎn)換
// 紅
Scanner(string: hex.substring(to: hex.index(hex.startIndex, offsetBy: 2))).scanHexInt32(&red)
// 綠
Scanner(string: hex.substring(with: hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4))).scanHexInt32(&green)
// 藍(lán)
Scanner(string: hex.substring(from: hex.index(startIndex, offsetBy: 4))).scanHexInt32(&blue)
return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
}
}
調(diào)用
"FF0000".uicolor() // red
給 UIColor
添加擴(kuò)展(實(shí)際代碼還是那些)
extension UIColor {
/// 用十六進(jìn)制顏色創(chuàng)建UIColor
///
/// - Parameter hexColor: 十六進(jìn)制顏色
/// - Parameter hexColor: 透明度
convenience init(hexColor: String, alpha: CGFloat = 1.0) {
// 存儲(chǔ)轉(zhuǎn)換后的數(shù)值
var red: UInt32 = 0, green: UInt32 = 0, blue: UInt32 = 0
var hex = self
// 如果傳入的十六進(jìn)制顏色有前綴,去掉前綴
if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2))
} else if hex.hasPrefix("#") {
hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1))
}
// 如果傳入的字符數(shù)量不足6位按照后邊都為0處理婿禽,當(dāng)然你也可以進(jìn)行其它操作
if characters.count < 6 {
for _ in 0..<6-characters.count {
hex += "0"
}
}
// 分別進(jìn)行轉(zhuǎn)換
// 紅
Scanner(string: hex.substring(to: hex.index(hex.startIndex, offsetBy: 2))).scanHexInt32(&red)
// 綠
Scanner(string: hex.substring(with: hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4))).scanHexInt32(&green)
// 藍(lán)
Scanner(string: hex.substring(from: hex.index(startIndex, offsetBy: 4))).scanHexInt32(&blue)
self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
}
}
調(diào)用
UIColor(hexColor: "FF0000") // red