I'm trying to determine whether a textColor should be black or white based on the background color, but it seem not to work. first of all i've created an extension which retrieve the rgb values. then i use below algorithm to calculate and then determine if the value is above 186. The issue is that everytime i run the algorithm it always return something around 1, which is way below the 186 which should be the middle which determine if text should be black or white. What am i doing wrong in order to calculate a value around 186? which i've found is what determine if it black or white from this question
How to decide font color in white or black depending on background color?
Extenstion
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r,g,b,a)
}
}
ViewDidLoad
let colorComp = UIColor(rgba: "#f2f2f2").components
let colorCheck = colorComp.red * 0.299 + colorComp.green * 0.587 + colorComp.blue * 0.114
print(colorCheck)
in this case red
, green
and blue
returns 0.949019607843137
each.