HexからUIColorの変換とUIColorをHexへ変換するUIColorのextensionです
extension UIColor {
class func hex (_ hexStr : String, alpha : CGFloat) -> UIColor {
var hexStr = hexStr
let alpha = alpha
hexStr = hexStr.replacingOccurrences(of: "#", with: "")
let scanner = Scanner(string: hexStr)
var color: UInt64 = 0
if scanner.scanHexInt64(&color) {
let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
let b = CGFloat(color & 0x0000FF) / 255.0
return UIColor(red:r,green:g,blue:b,alpha:alpha)
} else {
print("不正な値")
return UIColor.white
}
}
func toHex(alpha: Bool = false) -> String {
guard let components = cgColor.components, components.count >= 3 else {
return "ffffff"
}
let r = Float(components[0])
let g = Float(components[1])
let b = Float(components[2])
var a = Float(1.0)
if components.count >= 4 {
a = Float(components[3])
}
if alpha {
return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
} else {
return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
}
}
}
英字の大文字・小文字は気にしなくてOKです
let color1 = UIColor.hex("00ff00", alpha: 1)
let color2 = UIColor.hex("cccccc", alpha: 1)
hexへ戻す時は英字が大文字で返ってきます
let hex1 = color1.toHex() //00FF00
let hex2 = color2.toHex() //CCCCCC