使用HSL亮度系数从SKColor返回浅色

问题描述 投票:1回答:2

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

ios swift sprite-kit uicolor
2个回答
3
投票

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

0
投票

正如官方SKColor文档所说,在iOS上,SKColor只是一个UIColor。因此:

UIColor *uicolor = (UIColor *)skcolor;
CGFloat h, s, b, a; // lightness is called 'brightness' 
[uicolor getHue:&h saturation:&s brightness:&b alpha:&a];

// (play with your brightness value here)

SKColor *skcolor2 = (SKColor *)[UIColor colorWithHue:h saturation:s brightness:b alpha:a];
© www.soinside.com 2019 - 2024. All rights reserved.