Last active
May 22, 2024 15:51
-
-
Save stephancasas/d30de38ee4ff76c818632ff8a9a46b12 to your computer and use it in GitHub Desktop.
An extension on NSColor — offering initialization from and conversion to HEX string representations
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
// | |
// NSColor+HexString.swift | |
// | |
// Created by Stephan Casas on 5/22/24. | |
// | |
import Foundation; | |
import AppKit; | |
extension NSColor { | |
/// Create a new `NSColor` from the given string representation of a color's HEX or HEXA value. | |
convenience init?(hexString: String){ | |
var hexString = hexString.starts(with: "#") ? String(hexString.trimmingPrefix("#")) : hexString; | |
// Shorthand Format: #FFF | |
if hexString.count == 3 { | |
hexString = hexString.map({ "\($0)\($0)" }).joined() | |
} | |
// No-alpha Format: #FFFFFF | |
if hexString.count == 6 { | |
hexString = hexString.appending("FF"); | |
} | |
// Should have full-alpha format by now. | |
guard hexString.count == 8 else { | |
return nil; | |
} | |
let rgbaValues = stride(from: 0, to: 7, by: 2).map({ | |
let lowerBound = hexString.index(hexString.startIndex, offsetBy: $0); | |
let upperBound = hexString.index(after: lowerBound); | |
return String(hexString[lowerBound...upperBound]); | |
}).compactMap({ | |
Int($0, radix: 16) | |
}).map({ | |
CGFloat($0) / 255 | |
}); | |
self.init( | |
red: rgbaValues[0], | |
green: rgbaValues[1], | |
blue: rgbaValues[2], | |
alpha: rgbaValues[3]); | |
} | |
/// Create a new string representation of this color's HEXA value. | |
func toHexString() -> String { | |
"#" + [ | |
self.redComponent, | |
self.greenComponent, | |
self.blueComponent, | |
self.alphaComponent, | |
].map({ | |
UInt64($0 * 255) | |
}).map({ | |
_uint64ToString($0, radix: 16, uppercase: true) | |
}).joined() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment