如何计算两个 UIColor 实例之间的颜色对比度 [英] How to compute color contrast ratio between two UIColor instances

查看:33
本文介绍了如何计算两个 UIColor 实例之间的颜色对比度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a concise way to compute the color contrast ratio between two UIColor instances in Swift. I've found examples that are close but are overly complicated or outdated.

推荐答案

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

以下 UIColor 扩展包括静态和实例对比度方法.包含额外亮度方法,因为它由静态 contrastRatio(between:and:) 方法使用.

UIColor extension with contrast ratio and luminance

The following UIColor extension includes a static and instance contrast ratio method. A bonus luminance method is included since it is used by the static contrastRatio(between:and:) method.

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/#预定义https://github.com/dequelabs/axe-core/issues/1629#issuecomment-509880306

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

For predefinite colorspace (like in iOS see this https://developer.apple.com/videos/play/wwdc2016/712/) and also in general the correct THRESHOLD value is 0.04045 and not 0.03928.

这篇关于如何计算两个 UIColor 实例之间的颜色对比度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆