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