views:

397

answers:

2

Is it possible to draw a gradient in a path on the iPhone?

I'm looking for a replacement of the mac os x method -drawInBezierPath:(NSBezierPath *)path relativeCenterPosition:(NSPoint)relativeCenterPosition of NSGradient.

A: 

Yes, I think so if I understand your question. It is a bit involved but here is a good example of doing it:

http://cocoawithlove.com/2008/09/drawing-gloss-gradients-in-coregraphics.html

This is done with Cocoa and not Cocoa Touch but it translates with everything bu NSColor. You have to use UIColor instead. Basically, you have to create a gradient function and then use:

CGShadingCreateAxial()

to determine the value of your gradient.

Or are you wanting to have a line with a gradient?

Steven Noyes
+2  A: 

I think something like this will work:

CGContextSaveGState(c);
CGContextAddPath(c, path);
CGContextClip(c)

// make a gradient
CGColorRef colors[] = { topColor, bottomColor };
CFArrayRef colors = CFArrayCreate(NULL, (const void**)colors, sizeof(colors) / sizeof(CGColorRef), &kCFTypeArrayCallBacks);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colors, NULL);
CFRelease(colorSpace);
CFRelease(colors);

//  Draw a linear gradient from top to bottom
CGPoint start = ...
CGPoint end = ...
CGContextDrawLinearGradient(c, gradient, start, end, 0);

CFRelease(gradient);
CGContextRestoreGState(c);
Todd Ditchendorf
Thx a lot Todd!I already had the same code, but I forgot the CGContextClip after the CGContextAddPath ....
catlan
I'm trying to understand this code but "colors" is declared twice with different types. I'm not sure which one was being used in the subsequent calls.
progrmr
progrmr, it's typo, should be: CGColorRef colorRef[] = { topColor, bottomColor }; CFArrayRef colors = CFArrayCreate(NULL, (const void**)colorRef, sizeof(colorRef) / sizeof(CGColorRef),
digdog