Last active
September 16, 2023 03:55
-
-
Save yannickl/16f0ed38f0698d9a8ae7 to your computer and use it in GitHub Desktop.
Hex string <=> UIColor conversion in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
extension UIColor { | |
convenience init(hexString:String) { | |
let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) | |
let scanner = NSScanner(string: hexString) | |
if (hexString.hasPrefix("#")) { | |
scanner.scanLocation = 1 | |
} | |
var color:UInt32 = 0 | |
scanner.scanHexInt(&color) | |
let mask = 0x000000FF | |
let r = Int(color >> 16) & mask | |
let g = Int(color >> 8) & mask | |
let b = Int(color) & mask | |
let red = CGFloat(r) / 255.0 | |
let green = CGFloat(g) / 255.0 | |
let blue = CGFloat(b) / 255.0 | |
self.init(red:red, green:green, blue:blue, alpha:1) | |
} | |
func toHexString() -> String { | |
var r:CGFloat = 0 | |
var g:CGFloat = 0 | |
var b:CGFloat = 0 | |
var a:CGFloat = 0 | |
getRed(&r, green: &g, blue: &b, alpha: &a) | |
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 | |
return NSString(format:"#%06x", rgb) | |
} | |
} |
A simplified version of eMdOS with Alpha support and optionals. I use it to get the colors from a JSON without worrying if it's defined or not.
extension UIColor {
convenience init?(hexRGBA: String?) {
guard let rgba = hexRGBA, let val = Int(rgba.replacingOccurrences(of: "#", with: ""), radix: 16) else {
return nil
}
self.init(red: CGFloat((val >> 24) & 0xff) / 255.0, green: CGFloat((val >> 16) & 0xff) / 255.0, blue: CGFloat((val >> 8) & 0xff) / 255.0, alpha: CGFloat(val & 0xff) / 255.0)
}
convenience init?(hexRGB: String?) {
guard let rgb = hexRGB else {
return nil
}
self.init(hexRGBA: rgb + "ff") // Add alpha = 1.0
}
}
Usage:
let newColorWithAlpha = UIColor(hexRGBA: "#aabbccdd") ?? UIColor.white
let otherColor = UIColor(hexRGB: "#aabbcc") ?? UIColor.blue
@Invisible66 Updated it to Swift 4: https://gist.github.com/pvroosendaal/5aca45dff84590ab4d92d7b151b21839
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is working Swift 4?