-
-
Save omerucel/14180f291352e055983eb03f9a3371cf to your computer and use it in GitHub Desktop.
NSColor from hex or hexString
This file contains hidden or 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 Cocoa | |
extension String { | |
func conformsTo(pattern: String) -> Bool { | |
let pattern = NSPredicate(format:"SELF MATCHES %@", pattern) | |
return pattern.evaluate(with: self) | |
} | |
} | |
extension NSColor { | |
class func fromHex(hex: Int, alpha: Float) -> NSColor { | |
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 | |
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0 | |
let blue = CGFloat((hex & 0xFF)) / 255.0 | |
return NSColor(calibratedRed: red, green: green, blue: blue, alpha: 1.0) | |
} | |
class func fromHexString(hex: String, alpha: Float) -> NSColor? { | |
// Handle two types of literals: 0x and # prefixed | |
var cleanedString = "" | |
if hex.hasPrefix("0x") { | |
cleanedString = String(hex[(hex.index(hex.startIndex, offsetBy: 2))..<hex.endIndex]) | |
} else if hex.hasPrefix("#") { | |
cleanedString = String(hex[(hex.index(hex.startIndex, offsetBy: 1))..<hex.endIndex]) | |
} | |
// Ensure it only contains valid hex characters 0 | |
let validHexPattern = "[a-fA-F0-9]+" | |
if cleanedString.conformsTo(pattern: validHexPattern) { | |
var theInt: UInt32 = 0 | |
let scanner = Scanner(string: cleanedString) | |
scanner.scanHexInt32(&theInt) | |
let red = CGFloat((theInt & 0xFF0000) >> 16) / 255.0 | |
let green = CGFloat((theInt & 0xFF00) >> 8) / 255.0 | |
let blue = CGFloat((theInt & 0xFF)) / 255.0 | |
return NSColor(calibratedRed: red, green: green, blue: blue, alpha: 1.0) | |
} else { | |
return Optional.none | |
} | |
} | |
} | |
// Tests | |
let hex: Int = 0x222831 | |
let hexString: String = "#222831" | |
let hexStringAlt = "0x222831" | |
let hexColor = NSColor.fromHex(hex: hex, alpha: 1.0) | |
let hexColorFromString = NSColor.fromHexString(hex: hexString, alpha: 1.0)! | |
let hexColorFromStringAlt = NSColor.fromHexString(hex: hexStringAlt, alpha: 1.0)! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment