【问题标题】:How to replace bottom colour from black gradient to white gradient?如何将底部颜色从黑色渐变替换为白色渐变?
【发布时间】:2019-04-10 12:03:47
【问题描述】:

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

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

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】:

    试试

    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)
    

    输出将是:

    【讨论】:

    • 太棒了!!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多