Skip to content

Instantly share code, notes, and snippets.

@joaoffcosta
Created November 19, 2018 14:54
Show Gist options
  • Save joaoffcosta/a7ed0470dc7e5886d2544d9e328cce46 to your computer and use it in GitHub Desktop.
Save joaoffcosta/a7ed0470dc7e5886d2544d9e328cce46 to your computer and use it in GitHub Desktop.
UIColor+TextColor
import Foundation
import UIKit
extension UIColor {
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 1
var rgb: UInt64 = 0
scanner.scanHexInt64(&rgb)
self.init(rgb: Int(rgb))
}
convenience init(rgb: Int) {
let red = (rgb >> 16) & 0xFF
let green = (rgb >> 8) & 0xFF
let blue = rgb & 0xFF
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
var textColor: UIColor {
var hue: CGFloat = 0, saturation: CGFloat = 0, brightness: CGFloat = 0, alpha: CGFloat = 0
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return UIColor(hue: 0, saturation: 0, brightness: luminance > 0.5 ? 0 : 1, alpha: alpha)
}
var luminance: CGFloat {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let vs = [red,green,blue].map { $0 <= 0.03928 ? $0 / 12.92 : pow(($0 + 0.055) / 1.055, 2.4) }
return vs[0] * 0.2126 + vs[1] * 0.7152 + vs[2] * 0.0722
}
}
func label(_ color: UIColor) -> UILabel {
let lb = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 60, height: 20)))
lb.backgroundColor = color
lb.text = "CHAMP"
lb.textColor = color.textColor
lb.font = UIFont.systemFont(ofSize: 13)
lb.textAlignment = .center
lb.layer.cornerRadius = 10
lb.clipsToBounds = true
return lb
}
let lb1 = label(UIColor(rgb: 0xffffff))
let lb2 = label(UIColor(rgb: 0x000000))
let lb3 = label(UIColor(rgb: 0xe3e3e3))
let lb4 = label(UIColor(hex: "#0x3671f1"))
let lb5 = label(UIColor(rgb: 0xffd150))
let lb6 = label(UIColor(rgb: 0xf05322))
let lb7 = label(UIColor(rgb: 0xf8e71c))
let lb8 = label(UIColor(red: 255 / 255.0, green: 195 / 255.0, blue: 48 / 255.0, alpha: 1))
let lb9 = label(UIColor(red: 54 / 255.0, green: 81 / 255.0, blue: 241 / 255.0, alpha: 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment