如何将底色从黑色渐变替换为白色渐变?

时间:2019-04-10 12:03:47

标签: ios swift color-picker

我为颜色选择器工具创建了一个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))
        }
    }
}

所以有人让我知道什么变化使我获得了白色渐变吗?

1 个答案:

答案 0 :(得分: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)

输出将为:

enter image description here