Skip to content

Instantly share code, notes, and snippets.

@iamchiwon
Created December 5, 2022 08:51
Show Gist options
  • Save iamchiwon/0a75851ebd0d0f51e0b24eec89756c9e to your computer and use it in GitHub Desktop.
Save iamchiwon/0a75851ebd0d0f51e0b24eec89756c9e to your computer and use it in GitHub Desktop.
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, a: Int = 255) {
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 >> 24) & 0xFF,
green: (rgba >> 16) & 0xFF,
blue: (rgba >> 8) & 0xFF,
a: rgba & 0xFF
)
}
convenience init(gray: Int) {
self.init(red: gray, green: gray, blue: gray)
}
func alpha(_ a: CGFloat) -> UIColor {
let c = CIColor(cgColor: cgColor)
return UIColor(red: c.red, green: c.green, blue: c.blue, alpha: a)
}
var isDarkColor: Bool {
guard let rgb = cgColor.components else {
return false
}
let rValue = 0.2126 * rgb[0]
let gValue = 0.7152 * rgb[1]
let bValue = 0.0722 * rgb[2]
return (rValue + gValue + bValue) < 0.5
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment