Skip to content

Instantly share code, notes, and snippets.

@adamgraham
Last active May 27, 2019 23:26
Show Gist options
  • Save adamgraham/cc986d2e45acaedca55fa2007df6a785 to your computer and use it in GitHub Desktop.
Save adamgraham/cc986d2e45acaedca55fa2007df6a785 to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from ARGB (alpha, red, green, blue) colors.
/// An extension to provide conversion to and from ARGB (alpha, red, green, blue) colors.
extension UIColor {
/// The ARGB (alpha, red, green, blue) components of a color, in the range [0, 255].
struct ARGB: Hashable {
/// The alpha component of the color, in the range [0, 255].
var alpha: Int
/// The red component of the color, in the range [0, 255].
var red: Int
/// The green component of the color, in the range [0, 255].
var green: Int
/// The blue component of the color, in the range [0, 255].
var blue: Int
}
/// The ARGB (alpha, red, green, blue) components of the color, in the range [0, 255].
var argb: ARGB {
var (r, g, b, a) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
getRed(&r, green: &g, blue: &b, alpha: &a)
return ARGB(alpha: Int(round(a * 255.0)),
red: Int(round(r * 255.0)),
green: Int(round(g * 255.0)),
blue: Int(round(b * 255.0)))
}
/// Initializes a color from ARGB (alpha, red, green, blue) components.
/// - parameter argb: The components used to initialize the color.
convenience init(_ argb: ARGB) {
self.init(red: CGFloat(argb.red) / 255.0,
green: CGFloat(argb.green) / 255.0,
blue: CGFloat(argb.blue) / 255.0,
alpha: CGFloat(argb.alpha) / 255.0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment