0

I'm trying to set the color of a label according to the average color of the image behind it. If the average color is dark then set the UILabel text color as white, otherwise set it as black.

I followed the tutorial here for the average color logic which seems to work perfectly fine. Then I followed the accepted answer here for the logic on whether to set it as white or black which is where I think the problem is. For some reason the text color is always black no matter whether the image is black or white.

Here is my code in Swift:

var averageColor = thumbnailImage.image!.averageColor()
        var red = 0.0 as CGFloat, green = 0.0 as CGFloat, blue = 0.0 as CGFloat, alpha = 0.0 as CGFloat
        averageColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        let threshold = 150
        var bgDelta = ((red * 0.299) + (green * 0.587) + (blue * 0.114))

        if (255 - Double(bgDelta) > Double(threshold)) {
            self.eventName.textColor = .blackColor()
            println("black")
        } else {
            println("white")
            self.eventName.textColor = .whiteColor()
        }

Note: I've tried changing the threshold to no avail. The only value that seemed to yield results was 255 which is the maximum.

Community
  • 1
  • 1
cyril
  • 3,020
  • 6
  • 36
  • 61
  • Have you tried looking at what the different variables are when your code runs? What does `255 - Double(bgDelta)` evaluate to, for instance? – oisdk Jun 01 '15 at 18:24

1 Answers1

3

The RGBA components of UIColor are floating point numbers in the range 0.0 ... 1.0, so this

averageColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
var bgDelta = ((red * 0.299) + (green * 0.587) + (blue * 0.114))

also computes a value bgDelta in that range. Therefore the treshold must also be scaled to this range, something like

let threshold = CGFloat(150.0/255.0)
if 1.0 - bgDelta > threshold { ... }
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382