Last active
May 27, 2019 23:27
-
-
Save adamgraham/228549b8386704e89718cb3e40bdc4ad to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from RGBA (red, green, blue, alpha) colors.
This file contains 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
/// An extension to provide conversion to and from RGBA (red, green, blue, alpha) colors. | |
extension UIColor { | |
/// The RGBA (red, green, blue, alpha) components of a color, in the range [0, 255]. | |
struct RGBA: Hashable { | |
/// 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 alpha component of the color, in the range [0, 255]. | |
var alpha: Int | |
} | |
/// The RGBA (red, green, blue, alpha) components of the color, in the range [0, 255]. | |
var rgba: RGBA { | |
var (r, g, b, a) = (CGFloat(), CGFloat(), CGFloat(), CGFloat()) | |
getRed(&r, green: &g, blue: &b, alpha: &a) | |
return RGBA(red: Int(round(r * 255.0)), | |
green: Int(round(g * 255.0)), | |
blue: Int(round(b * 255.0)), | |
alpha: Int(round(a * 255.0))) | |
} | |
/// Initializes a color from RGBA (red, green, blue, alpha) components. | |
/// - parameter rgba: The components used to initialize the color. | |
convenience init(_ rgba: RGBA) { | |
self.init(red: CGFloat(rgba.red) / 255.0, | |
green: CGFloat(rgba.green) / 255.0, | |
blue: CGFloat(rgba.blue) / 255.0, | |
alpha: CGFloat(rgba.alpha) / 255.0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment