Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In iOS Development, using Core Graphics and/or Quartz 2D, how can I draw a circle filled with a gradient in such a manner that it looks like a sphere?

So far I have looked at using CGContextDrawLinearGradient() and CGContextDrawRadialGradient(), however, with the former I can't figure out how to make the gradient look like a sphere, and with the latter, I can't figure out how to make the gradient into the shape of a sphere, because every time I try, it turns out in the shape of the full cylinder instead of only a sphere.

The code I am using to current draw a 2D circle is shown below. I would like to use a gradient or any other method possible using only Core Graphics and/or Quartz 2D to fill the circle in a manner that makes it look like a sphere.

Current code for drawing a circle:

CGContextRef ctx = UIGraphicsGetCurrentContext();
float x = 20.0;
float y = 20.0;
float radius = 12.5;
CGContextFillEllipseInRect(ctx, CGRectMake(x, y, radius, radius);

P.S. - The above code works just as its supposed to, so in case there are any errors, they're just from my errors while typing the question, not while typing code into the actual file.

like image 432
cyndrus Avatar asked Jul 10 '11 03:07

cyndrus


1 Answers

I believe this is the effect you are looking for:

enter image description here

This is created using a radial gradient. The gradient starts with a radius of 0 and ends with a radius of the size of the circle. The center point of the start must be within the circle created by the end, or you will get a cone shape instead. Here is the code I used to make this image (a couple parts need to be translated to iOS before you use it):

CGContextRef ctxt = [[NSGraphicsContext currentContext] graphicsPort];
CGGradientRef gradient;
CGColorSpaceRef colorSpace;
CGFloat locations[] = {0.0,1.0};
CGFloat components[] = { 0.5,1.0,1.0,1.0, 0.25,0.5,0.5,1.0 };
colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
gradient = CGGradientCreateWithColorComponents(colorSpace,components,locations,
                                               sizeof(locations)/sizeof(CGFloat));
CGPoint start = {70.0,130.0}, end = {100.0,100.0};
CGFloat startRadius = 0.0, endRadius = 90.0;
CGContextDrawRadialGradient(ctxt,gradient,start,startRadius,end,endRadius,0);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
like image 139
ughoavgfhw Avatar answered Sep 18 '22 00:09

ughoavgfhw