Search code examples
iphoneiosuicolor

Figuring out the text color based on background view color iOS


I have these Views on which I add UILabels as text, The Views can have a background color that is dynamic and cannot be chosen,

Based on that I need to figure out the font color from only a set of three choices - two black or white or dark grey.

For example on a dark red background, a white font would be more suitable than black, while on a light yellow, perhaps a dark grey or black would be readable,

is there any index i could check from the background UIColor to see the illuminance?


Solution

  • Take a look at my UIColor category and the blackOrWhiteContrastingColor method. This will tell you what will look better out of black or white. You could extend that to support dark grey as well.

    Basically the way it works is to look at the luminosity difference between the target colour and black, and then between the target colour and white. It then chooses the biggest luminosity difference.