我需要确定选定的UIColor (由用户选择)是暗的还是亮的,这样我就可以更改位于该颜色之上的一行文本的颜色,以获得更好的可读性。
下面是一个用Flash/Actionscript编写的例子(带演示):http://web.archive.org/web/20100102024448/http://theflashblog.com/?p=173
有什么想法吗?
干杯,安德烈
更新
感谢大家的建议,下面是工作代码:
- (void) updateColor:(UIColor *) newColor
{
const CGFloat *componentColors = CGColorGetComponents(newColor.CGColor);
CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
if (colorBrightness < 0.5)
{
NSLog(@"my color is dark");
}
else
{
NSLog(@"my color is light");
}
}
再次感谢:)
发布于 2010-03-25 00:45:32
W3C具有以下特性:http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
如果只处理黑色或白色文本,请使用上面的颜色亮度计算。如果低于125,请使用白色文本。如果是125或以上,请使用黑色文本。
编辑1:偏向黑色文本。:)
编辑2:使用公式为((红值* 299) +(绿值* 587) +(蓝值* 114)) / 1000。
发布于 2015-03-14 10:51:53
下面是执行此检查的Swift (3)扩展。
此扩展适用于灰度颜色。但是,如果您使用RGB初始化器创建所有颜色,而不使用UIColor.black
和UIColor.white
等内置颜色,则可以删除额外的检查。
extension UIColor {
// Check if the color is light or dark, as defined by the injected lightness threshold.
// Some people report that 0.7 is best. I suggest to find out for yourself.
// A nil value is returned if the lightness couldn't be determined.
func isLight(threshold: Float = 0.5) -> Bool? {
let originalCGColor = self.cgColor
// Now we need to convert it to the RGB colorspace. UIColor.white / UIColor.black are greyscale and not RGB.
// If you don't do this then you will crash when accessing components index 2 below when evaluating greyscale colors.
let RGBCGColor = originalCGColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil)
guard let components = RGBCGColor?.components else {
return nil
}
guard components.count >= 3 else {
return nil
}
let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000)
return (brightness > threshold)
}
}
测试:
func testItWorks() {
XCTAssertTrue(UIColor.yellow.isLight()!, "Yellow is LIGHT")
XCTAssertFalse(UIColor.black.isLight()!, "Black is DARK")
XCTAssertTrue(UIColor.white.isLight()!, "White is LIGHT")
XCTAssertFalse(UIColor.red.isLight()!, "Red is DARK")
}
注意:已更新至Swift 3 12/7/18
发布于 2016-10-16 02:14:10
Swift3
extension UIColor {
var isLight: Bool {
var white: CGFloat = 0
getWhite(&white, alpha: nil)
return white > 0.5
}
}
// Usage
if color.isLight {
label.textColor = UIColor.black
} else {
label.textColor = UIColor.white
}
https://stackoverflow.com/questions/2509443
复制相似问题