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

So far I have looked at using CGContextDrawLinearGradient () and CGContextDrawRadialGradient (), however, with the former I cannot 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 in the shape of a sphere, because every time, when I try, it turns out in the form of a full cylinder, not just a sphere.

The code I'm using to draw a 2D circle is shown below. I would like to use a gradient or any other method that can only be used for Core Graphics and / or Quartz 2D to fill the circle so that it looks 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); 

PS - The above code works the way it was supposed to, so if there are any errors, they are simply from my mistakes when entering the question, and not when entering the code into the actual file.

+6
source share
1 answer

I believe this is the effect you are looking for:

enter image description here

This is created using a radial gradient. The gradient begins 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 create this image (a couple of parts need to be translated into iOS before using 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); 
+8
source

Source: https://habr.com/ru/post/892424/


All Articles