9

My view has a background image with a text label overlay What's the best/good dynamic way to determine text color based on the background image so it can be readable (For now, I'm only interested on determining if text color should be dark or light)

Thanks :)

Ed Liss
  • 546
  • 4
  • 16

2 Answers2

14

Find the average color with the link woz mentioned

Then style your text

CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
[averageColor getRed:&red green:&green blue:&blue alpha:&alpha];

int threshold = 105;
int bgDelta = ((red * 0.299) + (green * 0.587) + (blue * 0.114));

UIColor *textColor = (255 - bgDelta < threshold) ? [UIColor blackColor] : [UIColor whiteColor];

something like this.

You could also use the link above to get the UIColor from the image and use matt's category for UIColor to get light or dark.

Bot
  • 11,868
  • 11
  • 75
  • 131
  • Thanks man, It worked! BTW found the formula mentioned on this question http://stackoverflow.com/questions/2509443/check-if-uicolor-is-dark-or-bright#answer-2509596 – Ed Liss Oct 18 '13 at 19:01
  • Matts category is too big and worked not properly for me (black text on red background). Better use stackoverflow.com/a/18303674/5790492 – Nik Kov just now edit – Nike Kov Mar 10 '17 at 07:43
7

My first though is to find the average color of the image and set the text color based on that. Of course, images can contain light and dark areas, so the color you choose could be unreadable at times.

To find the average color of an image, try this:

http://www.bobbygeorgescu.com/2011/08/finding-average-color-of-uiimage/

Once you have the average color, check the red, green, and blue values. If they are "high enough" (whatever you define that as), use dark text, else use light text.

woz
  • 10,888
  • 3
  • 34
  • 64