本文介绍了使用HSL亮度系数从SKColor返回较浅的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iOS SKColor,我想将其转换为更浅的阴影(不透明,不透明/不透明),因此我想使用HSL亮度实现一个函数,该函数返回一个SKColor. IE.在函数内部,将原始SKColor转换为等效的HSL,然后对HSL亮度应用一个值以获得较浅的色度,然后将此HSL颜色转换回我可以使用的SKColor.

I have an iOS SKColor, that I want to convert to a lighter shade (that is opaque with no opacity/no transparency), therefore I would like to implement a function using the HSL lightness, that returns an SKColor. ie. inside the function, convert the original SKColor to the HSL equivalent, then apply a value to the HSL lightness to get a lighter color shade, then convert this HSL color back to an SKColor that I can use.

推荐答案

Xcode 8.2.1•Swift 3.0.2

Xcode 8.2.1 • Swift 3.0.2

extension UIColor {
    convenience init(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat = 1)  {
        let offset = saturation * (lightness < 0.5 ? lightness : 1 - lightness)
        let brightness = lightness + offset
        let saturation = lightness > 0 ? 2 * offset / brightness : 0
        self.init(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
    }
    var lighter: UIColor? {
        return applying(lightness: 1.25)
    }
    func applying(lightness value: CGFloat) -> UIColor? {
        guard let hsl = hsl else { return nil }
        return UIColor(hue: hsl.hue, saturation: hsl.saturation, lightness: hsl.lightness * value, alpha: hsl.alpha)
    }
    var hsl: (hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat)? {
        var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0, hue: CGFloat = 0
        guard
            getRed(&red, green: &green, blue: &blue, alpha: &alpha),
            getHue(&hue, saturation: nil, brightness: nil, alpha: nil)
        else { return nil }
        let upper = max(red, green, blue)
        let lower = min(red, green, blue)
        let range = upper - lower
        let lightness = (upper + lower) / 2
        let saturation = range == 0 ? 0 : range / (lightness < 0.5 ? lightness * 2 : 2 - lightness * 2)
        return (hue, saturation, lightness, alpha)
    }
}


let purple = UIColor(red: 160/255, green: 118/255, blue: 200/255, alpha: 1)
let lighter = purple.lighter

这篇关于使用HSL亮度系数从SKColor返回较浅的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 00:43