如何将底色从黑色渐变到白色渐变?

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

我为颜色选择工具创建了一个IBDesignable类。如下

here

我的问题是,它设置了黑色渐变。但我想设置一个白色渐变。以下是我的代码。

let saturationExponentTop:Float = 0.0
let saturationExponentBottom:Float = 1.3

@IBInspectable var elementSize: CGFloat = 1.0 {
    didSet {
        setNeedsDisplay()
    }
}     
override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    for y : CGFloat in stride(from: 0.0 ,to: rect.height, by: elementSize) {
        var saturation = y < rect.height / 2.0 ? CGFloat(2 * y) / rect.height : 2.0 * CGFloat(rect.height - y) / rect.height
        saturation = CGFloat(powf(Float(saturation), y < rect.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = y < rect.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect.height - y) / rect.height
        for x : CGFloat in stride(from: 0.0 ,to: rect.width, by: elementSize) {
            let hue = x / rect.width
            let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y:y, width:elementSize,height:elementSize))
        }
    }
}

所以任何人都让我知道什么变化让我白色渐变?

ios swift color-picker
1个回答
1
投票

尝试

override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        for y : CGFloat in stride(from: 0.0 ,to: rect.height, by: elementSize) {
            var saturation = y < rect.height / 2.0 ? CGFloat(2 * y) / rect.height : 2.0 * CGFloat(rect.height - y) / rect.height
            saturation = CGFloat(powf(Float(saturation), y < rect.height / 2 ? saturationExponentTop : saturationExponentBottom))
            let brightness = CGFloat(1.0)

            for x : CGFloat in stride(from: 0.0 ,to: rect.width, by: elementSize) {
                let hue = x / rect.width
                let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
                context!.setFillColor(color.cgColor)
                context!.fill(CGRect(x:x, y:y, width:elementSize,height:elementSize))
            }
        }
    }

改变在brightness的地方

 let brightness = CGFloat(1.0)

OutPut将是:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.