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

ios - 如何从黑色渐变到白色渐变替换底色?-LMLPHP

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

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))
        }
    }
}

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

最佳答案

尝试

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)

输出将是:

ios - 如何从黑色渐变到白色渐变替换底色?-LMLPHP

关于ios - 如何从黑色渐变到白色渐变替换底色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55612125/

10-10 21:07