Skip to content

Instantly share code, notes, and snippets.

@userow
Created August 25, 2020 11:36
Show Gist options
  • Save userow/7760a10b43d24b03e905fea916b0ffb4 to your computer and use it in GitHub Desktop.
Save userow/7760a10b43d24b03e905fea916b0ffb4 to your computer and use it in GitHub Desktop.
public enum Color: UInt32, ColorRepresentable {
case secondary = 0x9B9B9B
case accent = 0x0083C1
case success = 0x7ED321
public enum Complete: UInt32, ColorRepresentable {
case background = 0x374162
}
}
protocol ColorRepresentable: RawRepresentable { }
extension ColorRepresentable where Self.RawValue == UInt32 {
/// Returns opaque color
var opaque: UIColor {
return UIColor(rgb: self.rawValue)
}
/**
Returns color with alpha component.
- parameter alpha: Alpha component of color.
- returns: New color.
*/
func alpha(_ alpha: CGFloat) -> UIColor {
return self.opaque.withAlphaComponent(alpha)
}
}
extension UIColor {
// MARK: -
// MARK: Subtypes
enum Channel: UInt32 {
case red = 3
case green = 2
case blue = 1
case alpha = 0
}
/**
Creates opaque color with RGB hex value.
- parameter rgb: Color in hex UInt32 value of form 00RRGGBB, where each letter pair is 1 byte.
- return: New color.
*/
convenience init(rgb: UInt32) {
self.init(rgba: (rgb << 😍 | 0xFF)
}
/**
Creates opaque color with RGBA hex value.
- parameter rgb: Color in hex UInt32 value of form RRGGBBAA, where each letter pair is 1 byte.
- return: New color.
*/
convenience init(rgba: UInt32) {
let channel: (Channel) -> CGFloat = { CGFloat((rgba >> ($0.rawValue * 8)) & 0xFF) / 255.0 }
self.init(red: channel(.red), green: channel(.green), blue: channel(.blue), alpha: channel(.alpha))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment