views:

609

answers:

1

The gradient in question is Figure 8-5 from the Quartz 2D Programming Guide, "A radial gradient that varies between a point and a circle".

I'm trying to build a CGGradient object (not a CGShading object, which might be the problem) like so:

    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colors[] =
    {
        0, 0, 0, 0.9,
        0, 0, 0, 0
    };
    CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*sizeof(CGFloat)));
    CGContextClipToRect(context, rect);
    CGContextDrawRadialGradient(context, gradient, startCenter, startRadius, endCenter, endRadius, gradientDrawingOptions);
    CGGradientRelease(gradient);
    CGColorSpaceRelease(rgb);

Of course, that isn't exactly right -- the centre points and radii are correct, but the actual gradient doesn't look the same. I just wish Apple had provided the source code for each example! >:(

+1  A: 

UPDATE: These color values add the shading on top of other content (drawing from a point out to a circle):

CGFloat colors[] =
{
    0.0f, 0.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 0.0f, 0.75f
};

Using these color values is pretty close (drawing from a point out to a circle):

CGFloat colors[] =
{
    0.0f, 1.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 0.0f, 0.75f
};
gerry3
Let's say I already have a filled circle underneath it that (with an arbitrary colour). How can I draw a gradient over top to approximate the shading?
Shaggy Frog
Okay, so given your new set of values, you must be drawing from the inside of the circle out, correct? Right now I'm drawing from the outside in. (Our two arrays are almost identical that way)
Shaggy Frog
Correct. Good point, you did not post that code, so there was no way to know. What is the issue then? It looks very close...
gerry3
For some reason, to my eye, it seems a little off. Here's the rendering in the simulator (my "end circle" is located around the edge on the right side): http://www.shaggyfrog.com/junk/shaded-circle.png How does it look to your eye?
Shaggy Frog
Where is your point relative to your circle? My circle has a radius of 100 and the point's center is up and to the left of the circle's center by 50 each.
gerry3
My start circle has a radius of 150. The end circle has a radius of 0, with a centre located on the edge of the start circle (just off the 3 o'clock mark)
Shaggy Frog
That makes sense, but if you want it to look like that example from Apple, the point (circle with radius 0) should be between 10 and 11 o'clock and inside the (outer) circle rather than on the edge...
gerry3
The default range of all four color components is 0.0 to 1.0. “0, 200, 100” is effectively 0.0, 1.0, 1.0, or pure cyan (assuming these are RGBA and not ARGB).
Peter Hosey
Good call. I updated my code.
gerry3