随机生成的CGGradient不会显示

时间:2015-07-04 15:15:26

标签: ios swift core-graphics gradient

我正在编写一个生成随机渐变的应用,并使用自定义UIView类在屏幕上显示它们。因为我有更多计划的应用程序功能,所以我选择为梯度赋予自己的类。生成渐变的代码如下:

import UIKit

class Gradient {

var topColor = UIColor()
var bottomColor = UIColor()
var gradient: CGGradientRef?

func generateGradient() -> CGGradientRef {

    var red = CGFloat(arc4random_uniform(256))
    var green = CGFloat(arc4random_uniform(256))
    var blue = CGFloat(arc4random_uniform(256))

    topColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)

    red = CGFloat(arc4random_uniform(256))
    green = CGFloat(arc4random_uniform(256))
    blue = CGFloat(arc4random_uniform(256))

    bottomColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)

    let gradientColors = [topColor.CGColor, bottomColor.CGColor]
    let gradientStops:[CGFloat] = [0, 1.0]
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    let generatedGradient = CGGradientCreateWithColors(colorSpace, gradientColors, gradientStops)

    return generatedGradient

}

init() {
    gradient = self.generateGradient()
}

}

显示渐变的渐变查看器类为:

import UIKit

@IBDesignable class Gradient_Viewer: UIView {

override func drawRect(rect: CGRect) {

    let background = Gradient()
    let context = UIGraphicsGetCurrentContext()
    let startPoint = CGPoint.zeroPoint
    let endPoint = CGPoint(x: 0, y: self.bounds.height)

    CGContextDrawLinearGradient(context, background.gradient, startPoint, endPoint, 0)

}

}

渐变生成有问题,还是我没有正确访问渐变?

1 个答案:

答案 0 :(得分:0)

@IBDesignable class Gradient_Viewer: UIView {
    var random8bit: CGFloat {
        return CGFloat(arc4random_uniform(256))/255.0
    }
    var gradient: CGGradientRef {
        return CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [UIColor(red: random8bit, green: random8bit, blue: random8bit, alpha: 1.0).CGColor, UIColor(red: random8bit, green: random8bit, blue: random8bit, alpha: 1.0).CGColor], [0, 1.0])
    }
    override func drawRect(rect: CGRect) {
        CGContextDrawLinearGradient(UIGraphicsGetCurrentContext(), gradient, CGPoint.zeroPoint, CGPoint(x: 0, y: self.bounds.height), 0)
    }
}