3

I tried to draw a Gradient Dot, but the CGGradientCreateWithColors always returns nil. I am new to Swift and Objective C (started today, but made some Apps with Xamarin). Can please anyone explain what is wrong with the following code?

func initFields(){
    var startColor = UIColor.blueColor().CGColor
    var endColor = UIColor.greenColor().CGColor
    var colors: CFArray = [startColor, endColor]

    Gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), colors, [0, 10])
}
func DrawSomething(){
    UIGraphicsBeginImageContext(frame.size)
    CGContextDrawRadialGradient(UIGraphicsGetCurrentContext(), Gradient!, TouchLocation!, 10, TouchLocation!, 10, 0)
}
SYNT4X
  • 210
  • 2
  • 15

1 Answers1

1

From the CGGradientCreateWithColors() documentation:

... each location must be a CGFloat value in the range of 0 to 1, inclusive.

So change [0, 10] to [0, 1] in the creation of the gradient.

The color at location 0 is mapped to the starting circle and the color at location 1 is mapped to the ending circle.

It also seems strange that the starting circle and the ending circle are identical in your code.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thank you. That was helpfull getting the Gradient. I changed the End Location for it too. But it doesn´t draw anything, is this all I have to do? Begin an ImageContext and call the Draw function? – SYNT4X Jul 03 '14 at 19:43
  • @NormanSchütt: `UIGraphicsBeginImageContext` is used to draw into a bitmap (example here: http://stackoverflow.com/questions/4683448/uigraphicsbeginimagecontext-vs-cgbitmapcontextcreate). - For custom drawing in a UIView subclass, you implement `drawRect:`. – Martin R Jul 03 '14 at 19:48