PappaGee PappaGee - 5 months ago 33
iOS Question

Core Graphics & Gradients

could some one tell me why i have error when declaring let = Gradient

contectual type CFArray can not be used with array literal


with this code - which is just a background gradient, which i thought would be better than using a vector..

override func drawRect(rect: CGRect) {

//// General Declarations
let context = UIGraphicsGetCurrentContext()

//// Color Declarations
let gradientColor = UIColor(red: 0.180, green: 0.808, blue: 0.831, alpha: 0.196)
let gradientColor2 = UIColor(red: 0.200, green: 0.282, blue: 0.392, alpha: 1.000)

//// Gradient Declarations
let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [gradientColor2.CGColor, gradientColor2.blendedColorWithFraction(0.5, ofColor: gradientColor).CGColor, gradientColor.CGColor], [0, 1, 1])!

//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 375, height: 667))
CGContextSaveGState(context)
rectanglePath.addClip()
CGContextDrawLinearGradient(context, gradient, CGPoint(x: 187.5, y: -0), CGPoint(x: 187.5, y: 667), CGGradientDrawingOptions())
CGContextRestoreGState(context)



}


}

Answer

So all that means is that you can't pass a swift array to the CGGradientCreateWithColors function. You need to turn that array in a CFArray like so:

let gradientArray = [gradientColor2.CGColor, gradientColor.CGColor]
let arrayPointer = UnsafeMutablePointer<UnsafePointer<Void>>(gradientArray)
let cfArray = CFArrayCreate(nil, arrayPointer, gradientArray.count, nil)

Then pass that CFArray reference to the function:

let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), cfArray, [0, 1, 1])!
Comments