반응형
//Input Format : String "0x(16진수 RGB색상 값)"
let input = "0x554433"//"0x13123ac"
//https://stackoverflow.com/questions/27189338/swift-native-functions-to-have-numbers-as-hex-strings
// Int(_, radix: ) can't deal with the '0x' prefix. NSScanner can handle hex
// with or without the '0x' prefix
let scanner = Scanner(string: input)
var value: UInt64 = 0
if scanner.scanHexInt64(&value) { // value가 hex값으로 변환한 Int값.
print("Decimal: \(value) ::: \(Int(value))")
//UIColor(netHex: Int)를 이용해서 색상 변화 가능
//self.contentView.backgroundColor = .init(netHex: Int(value))
//아래는 값 확인용 코드.
let test2 = String(value, radix: 16)
print("HexCheck: \(test2)")
print("Hex: 0x\(String(value, radix: 16))")
/*
let text3 = 0x554433
let red = (text3 >> 16) & 0xff
let green = (text3 >> 8) & 0xff
let blue = text3 & 0xff
print("CheckRGB ::: \n\(red) || \(green) || \(blue)\n\(text3 >> 16) || \(text3 >> 8) || \(text3)")
*/
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: alpha)
}
//아래의 init(netHex: Int)들의 경우, netHex parameter에 0x000000~0xffffff값을 넣으면 된다.
// UIColor(netHex:0xFFFFFF)
convenience init(netHex:Int) {
let red = (netHex >> 16) & 0xff
let green = (netHex >> 8) & 0xff
let blue = netHex & 0xff
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
// UIColor(netHex:0xFFFFFF, alpha:1.0)
convenience init(netHex:Int, alpha:CGFloat) {
let red = (netHex >> 16) & 0xff
let green = (netHex >> 8) & 0xff
let blue = netHex & 0xff
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
//string input을 이용해서 직접적으로 변환을 시켜주는 코드.
convenience public init?(hex: String, _ alpha: CGFloat = 1.0) {
let r, g, b, a: CGFloat
if hex.hasPrefix("#") {
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
if hexColor.count == 6 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255
g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255
b = CGFloat((hexNumber & 0x0000ff)) / 255
a = alpha
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
}
반응형
'모바일 프로그래밍 > IOS참고자료' 카테고리의 다른 글
[iOS] Debug, Release scheme setting - (정리 전) (0) | 2020.11.05 |
---|---|
[iOS] Debug print (0) | 2020.11.04 |
iOS 참고자료 (0) | 2020.11.03 |
TableView Cell Swipe Action Example (0) | 2020.10.14 |
[iOS]Gradient 관련 코드(정리 전 원본 코드) (0) | 2020.09.01 |