0

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.

Community
  • 1
  • 1
Peter Pik
  • 11,023
  • 19
  • 84
  • 142
  • 2
    That seems right. `components` is defined to return a value between 0.0 and 1.0. The return value you show looks good for 'f2' divided by 'ff'. If you want a value in the range 0..255, you need to multiply to scale your result. – Phillip Mills Oct 05 '15 at 13:28

1 Answers1

1

The RGB range is from 0 (blak) to 255 (white) but in this case the range is 0 to 1. You should calculate the new value with this operation:

Value = (1/255)*186 = 0.729;

0xF2 = 242 dec = 242/255 = 0.949

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
  • So where is it i determine whether it is above or below 186 here? – Peter Pik Oct 05 '15 at 14:08
  • After your function "let colorComp = UIColor(rgba: "#f2f2f2").components" you can convert the colorspace from 0.0 / 1.0 into colorspace 1 / 255 of R G and B and then for each color check if the value is > or < 186. – Lorenzo Oct 05 '15 at 14:15