How to compute color contrast ratio between two UIColor instances

后端 未结 2 2139
青春惊慌失措
青春惊慌失措 2021-02-15 17:35

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 compli

2条回答
  •  野性不改
    2021-02-15 18:20

    If building for WatchOS where CoreImage is not available or for whatever reason you do not want to rely on CoreImage and therefore CIColor is unavailable, replace @Mobile Dan's luminance function with:

      private func luminance() -> CGFloat {
      // https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
    
        func adjust(colorComponent: CGFloat) -> CGFloat {
          return (colorComponent < 0.03928) ? (colorComponent / 12.92) : pow((colorComponent + 0.055) / 1.055, 2.4)
        }
    
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)
    
        return 0.2126 * adjust(colorComponent: red)
          + 0.7152 * adjust(colorComponent: green)
          + 0.0722 * adjust(colorComponent: blue)
      }
    

提交回复
热议问题