Last active
August 23, 2019 11:03
-
-
Save P0ed/6ade806c024c5a6689d39eeff7c6b0c8 to your computer and use it in GitHub Desktop.
Advanced color literals
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 Fx | |
import UIKit | |
public struct RGBA { | |
var r: UInt8 | |
var g: UInt8 | |
var b: UInt8 | |
var a: UInt8 | |
} | |
public extension UIColor { | |
convenience init(_ value: RGBA) { | |
self.init( | |
red: CGFloat(value.r) / 255, | |
green: CGFloat(value.g) / 255, | |
blue: CGFloat(value.b) / 255, | |
alpha: CGFloat(value.a) / 255 | |
) | |
} | |
convenience init(light: RGBA, dark: RGBA) { | |
let lightColor = UIColor(light) | |
let darkColor = UIColor(dark) | |
self.init(dynamicProvider: { traits in | |
traits.userInterfaceStyle == .dark ? darkColor : lightColor | |
}) | |
} | |
var light: UIColor { | |
return resolvedColor(with: UITraitCollection(userInterfaceStyle: .light)) | |
} | |
var dark: UIColor { | |
return resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark)) | |
} | |
var rgba: RGBA { | |
var red = 0 as CGFloat | |
var green = 0 as CGFloat | |
var blue = 0 as CGFloat | |
var alpha = 0 as CGFloat | |
getRed(&red, green: &green, blue: &blue, alpha: &alpha) | |
return RGBA( | |
r: UInt8(red * 255), | |
g: UInt8(green * 255), | |
b: UInt8(blue * 255), | |
a: UInt8(alpha * 255) | |
) | |
} | |
var rgbHex: Int { | |
let rgba = self.rgba | |
return Int(rgba.r) << 16 | Int(rgba.g) << 8 | Int(rgba.b) | |
} | |
var rgbHexString: String { return String(format: "%06x", rgbHex) } | |
} | |
extension RGBA: ExpressibleByIntegerLiteral { | |
public init(integerLiteral value: Int) { | |
let byte = { idx in UInt8((value & (0xFF << (8 * idx))) >> (8 * idx)) } | |
self = RGBA(r: byte(2), g: byte(1), b: byte(0), a: 255) | |
} | |
} | |
func * (rgba: RGBA, alpha: CGFloat) -> RGBA { | |
return modify(rgba) { $0.a = UInt8(CGFloat($0.a) * alpha.clamped(to: 0...1)) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: