Last active
June 15, 2018 09:34
-
-
Save 4np/f24239bcf18a985907e7aabe76de0d93 to your computer and use it in GitHub Desktop.
Cross-platform hex colors for UIColor and NSColor
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
// | |
// UXColor+Hex.swift | |
// | |
// Created by Jeroen Wesbeek on 15/06/2018. | |
// Copyright © 2018 Jeroen Wesbeek. All rights reserved. | |
// | |
import Foundation | |
#if os(iOS) || os(tvOS) || os(watchOS) | |
import UIKit | |
public typealias UXColor = UIColor | |
#endif | |
#if os(OSX) | |
import Cocoa | |
public typealias UXColor = NSColor | |
#endif | |
/// Initialize a color by hexadecimal value | |
extension UXColor { | |
convenience init(hex hexString: String) { | |
var hex = hexString.hasPrefix("#") ? String(hexString.dropFirst()) : hexString | |
// change 3 char color to 6 char color | |
if hex.count == 3 { | |
for (index, char) in hex.enumerated() { | |
hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2)) | |
} | |
} | |
// we expect a 6 char color | |
guard hex.count == 6, let color = Int(hex, radix: 16) else { | |
// initiale with black | |
self.init(hex: "000") | |
return | |
} | |
let red = CGFloat((color >> 16 & 0xFF)) / 255.0 | |
let green = CGFloat((color >> 8 & 0xFF)) / 255.0 | |
let blue = CGFloat((color & 0xFF)) / 255.0 | |
self.init(red: red, green: green, blue: blue, alpha: 1.0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment