你可以像这样做:
extension UIColor
{
var isDarkColor: Bool {
var r, g, b, a: CGFloat
(r, g, b, a) = (0, 0, 0, 0)
self.getRed(&r, green: &g, blue: &b, alpha: &a)
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
return lum < 0.50
}
}
这将计算颜色的亮度,并确定它是否高于某个阈值。然后说 myLabel.textColor = view.backgroundColor?.isDarkColor == true ? .white : .black
extension UIColor
{
var isDarkColor: Bool {
var r, g, b, a: CGFloat
(r, g, b, a) = (0, 0, 0, 0)
self.getRed(&r, green: &g, blue: &b, alpha: &a)
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
return lum < 0.50
}
}
extension Color{
var isDarkColor : Bool {
return UIColor(self).isDarkColor
}
}
extension UIColor {
convenience init(
light lightModeColor: @escaping @autoclosure () -> UIColor,
dark darkModeColor: @escaping @autoclosure () -> UIColor
) {
self.init { traitCollection in
switch traitCollection.userInterfaceStyle {
case .light:
return lightModeColor()
case .dark:
return darkModeColor()
case .unspecified:
return lightModeColor()
@unknown default:
return lightModeColor()
}
}
}
/// returns true if is a dark color
var isDarkColor: Bool {
var r, g, b, a: CGFloat
(r, g, b, a) = (0, 0, 0, 0)
self.getRed(&r, green: &g, blue: &b, alpha: &a)
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
return lum < 0.45
}
/// Generates contrasting color for dark and light userInterfaceStyles
/// - Returns: UIColor.white for dark colors else return UIColor.black
func contrastingColor() -> UIColor {
let dark = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
let light = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
return UIColor(light: light.isDarkColor ? .white : .black,
dark: dark.isDarkColor ? .white : .black)
}
}
代码参考 对比文本
let backgroundColor = UIColor.black
let contrastingColor = backgroundColor.contrastingColor()