Last active
August 6, 2021 10:05
-
-
Save dfelber/783a46fae5f8978252e6cecff7b58663 to your computer and use it in GitHub Desktop.
Extension for UIColor and NSColor to initialize them with hexadecimal values like `0xcf0b69`
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
#if os(OSX) | |
import AppKit | |
typealias Color = NSColor | |
#elseif os(iOS) || os(tvOS) | |
import UIKit | |
typealias Color = UIColor | |
#endif | |
extension Color | |
{ | |
/// Initializes a `NSColor` or `UIColor` object from a (hexadecimal) `UInt32` value. | |
/// | |
/// - parameter hex: The (hexadecimal) value with 8 bits per color channel. | |
/// `0xRRGGBB` e.g. `0xff0000` for red. | |
/// - parameter alpha: The desired value of the alpha channel of the color to create. | |
/// Default is 1.0 | |
/// Should be in the range of 0.0...1.0 | |
/// | |
convenience init(hex: UInt32, alpha a: CGFloat = 1.0) { | |
let r = CGFloat((hex >> 16) & 0xFF) / 255.0 | |
let g = CGFloat((hex >> 8) & 0xFF) / 255.0 | |
let b = CGFloat((hex) & 0xFF) / 255.0 | |
self.init(red: r, green: g , blue: b , alpha: a) | |
} | |
} | |
#if os(OSX) | |
NSColor(hex: 0xffffff) | |
NSColor(hex: 0x000000, alpha: 0.9) | |
#elseif os(iOS) || os(tvOS) | |
UIColor(hex: 0xff00ff) | |
UIColor(hex: 0xcf0b69, alpha: 0.9) | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment