Skip to content

Instantly share code, notes, and snippets.

@rbresjer
Created January 26, 2017 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbresjer/51f9b39346e90c1c2485eb98b1ad2d46 to your computer and use it in GitHub Desktop.
Save rbresjer/51f9b39346e90c1c2485eb98b1ad2d46 to your computer and use it in GitHub Desktop.
UIColor extension with hex initializers
fileprivate extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(red: Int, green: Int, blue: Int, opacity: CGFloat) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
assert(opacity >= 0 && opacity <= 1, "Invalid alpha component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: opacity)
}
convenience init(hex: Int) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff)
}
convenience init(hex: Int, alpha: CGFloat) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff, opacity: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment