| 문자열 헥사 코드로 컬러 값 사용하기
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: Double = 1.0) {
self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: alpha)
}
static func hexStringToUIColor (hex:String, alpha: CGFloat = 1.0) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha
)
}
}
EX)
let color = UIColor(red: 0, green: 0, blue: 256, alpha: 1.0)
let color = UIColor.hexStringToUIColor(hex: "#ff00ff", alpha: 1.0)
'Swift > UIColor 및 CALayer' 카테고리의 다른 글
[SWIFT]그라데이션 Border 및 백그라운드 색상 넣기 (0) | 2023.07.20 |
---|