Swift 16进制转颜色
extension UIColor{
class func colorWithHexString(hex:String,alpha:CGFloat) -> UIColor {
var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if cString.hasPrefix("#") {
let index = cString.index(after: cString.startIndex)
cString = cString.substring(from: index)
}
if cString.characters.count != 6 {
return UIColor.black
}
let rRange = cString.startIndex ..< cString.index(cString.startIndex, offsetBy: 2)
let rString = cString.substring(with: rRange)
print(rString);
let gRange = cString.index(cString.startIndex, offsetBy: 2) ..< cString.index(cString.startIndex, offsetBy: 4)
let gString = cString.substring(with: gRange)
print(gString);
let bRange = cString.index(cString.startIndex, offsetBy: 4) ..< cString.index(cString.startIndex, offsetBy: 6)
let bString = cString.substring(with: bRange)
print(bString);
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: alpha)
}
}