Why won't the average color yield to a result other than black?
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.
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 { ... }
链接地址: http://www.djcxy.com/p/87330.html
下一篇: 为什么黑色以外的结果的平均颜色屈服?