extension UIColor {
convenience init(hex16: UInt16) {
let alpha = CGFloat((hex16 >> 12) & 0xf) / 0xf
let red = CGFloat((hex16 >> 8) & 0xf) / 0xf
let green = CGFloat((hex16 >> 4) & 0xf) / 0xf
let blue = CGFloat(hex16 & 0xf) / 0xf
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
convenience init (hex32: UInt32) {
let alpha = CGFloat((hex32 >> 24) & 0xff) / 0xff
let red = CGFloat((hex32 >> 16) & 0xff) / 0xff
let green = CGFloat((hex32 >> 8) & 0xff) / 0xff
let blue = CGFloat(hex32 & 0xff) / 0xff
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
convenience init?(hexString: String) {
if !hexString.hasPrefix("#") {
return nil
}
var hexStr = hexString
hexStr.remove(at: hexStr.startIndex)
switch hexStr.characters.count {
case 3:
hexStr = "f" + hexStr
fallthrough
case 4:
guard let hex16 = UInt16(hexStr, radix: 16) else {
return nil
}
self.init(hex16: hex16)
case 6:
hexStr = "ff" + hexStr
fallthrough
case 8:
guard let hex32 = UInt32(hexStr, radix: 16) else {
return nil
}
self.init(hex32: hex32)
default:
return nil
}
}
}
// 결과보기
UIColor(hex16: 0xf0f0) // r 0,0, g 1.0, b 0.0, a 1.0
UIColor(hexString: "#707070") // r.0.439, g 0.439, b 0.439, a 1.0
UIColor(hexString: "#888") // r 0.533, g 0.533, b 0.533, a 1.0
참조 : https://swifter.kr/2016/08/14/swift3-16%EC%A7%84%EC%88%98%EB%A1%9C-uicolor-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/
*모든 레퍼런스를 제공해주시는 개발자님들께 항상 감사드립니다.