Skip to content

Instantly share code, notes, and snippets.

@mjhassan
Created January 14, 2020 03:12
Show Gist options
  • Select an option

  • Save mjhassan/476330bc518c40986910eb37d214892f to your computer and use it in GitHub Desktop.

Select an option

Save mjhassan/476330bc518c40986910eb37d214892f to your computer and use it in GitHub Desktop.
Convert any color format to UIColor
import UIKit
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
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: CGFloat(a) / 255.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
convenience init(rgba: Int) {
self.init(
red: (rgba >> 16) & 0xFF,
green: (rgba >> 8) & 0xFF,
blue: rgba & 0xFF,
a: (rgba >> 24) & 0xFF
)
}
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt64()
Scanner(string: hex).scanHexInt64(&int)
let a, r, g, b: UInt64
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment