Skip to content

Instantly share code, notes, and snippets.

@P0ed
Last active August 23, 2019 11:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save P0ed/6ade806c024c5a6689d39eeff7c6b0c8 to your computer and use it in GitHub Desktop.
Save P0ed/6ade806c024c5a6689d39eeff7c6b0c8 to your computer and use it in GitHub Desktop.
Advanced color literals
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)) }
}
@P0ed
Copy link
Author

P0ed commented Aug 23, 2019

Usage:

public extension UIColor {
	static let textSecondary = UIColor(light: 0x9A938D, dark: 0xFFFFFF * 0.6)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment