我正在寻找一种简洁的方法来计算Swift中两个UIColor实例之间的颜色对比度。我发现了一些接近但过于复杂或过时的示例。

最佳答案

带有对比度和亮度的UIColor扩展

以下UIColor扩展包括静态和实例对比度比率方法。由于它是由静态contrastRatio(between:and:)方法使用的,因此包含了额外的亮度方法。

import UIKit

extension UIColor {

    static func contrastRatio(between color1: UIColor, and color2: UIColor) -> CGFloat {
        // https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests

        let luminance1 = color1.luminance()
        let luminance2 = color2.luminance()

        let luminanceDarker = min(luminance1, luminance2)
        let luminanceLighter = max(luminance1, luminance2)

        return (luminanceLighter + 0.05) / (luminanceDarker + 0.05)
    }

    func contrastRatio(with color: UIColor) -> CGFloat {
        return UIColor.contrastRatio(between: self, and: color)
    }

    func luminance() -> CGFloat {
        // https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests

        let ciColor = CIColor(color: self)

        func adjust(colorComponent: CGFloat) -> CGFloat {
            return (colorComponent < 0.04045) ? (colorComponent / 12.92) : pow((colorComponent + 0.055) / 1.055, 2.4)
        }

        return 0.2126 * adjust(colorComponent: ciColor.red) + 0.7152 * adjust(colorComponent: ciColor.green) + 0.0722 * adjust(colorComponent: ciColor.blue)
    }
}

使用范例
// static method
let contrastRatio1 = UIColor.contrastRatio(between: UIColor.black, and: UIColor.white)
print(contrastRatio1) // 21.0

// instance method
let contrastRatio2 = UIColor.black.contrastRatio(with: UIColor.white)
print(contrastRatio2) // 21.0

笔记

这些链接如下:
https://www.w3.org/TR/css-color-4/#predefined
https://github.com/dequelabs/axe-core/issues/1629#issuecomment-509880306

对于预定的色彩空间(例如,在iOS中,请参见https://developer.apple.com/videos/play/wwdc2016/712/),并且通常,正确的THRESHOLD值为 0.04045 而不是0.03928。

关于ios - 如何计算两个UIColor实例之间的颜色对比度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42355778/

10-09 08:09