1

How can I draw a sector (filled arc) with radial gradient in objective c (Core Graphics) I use

CGContextDrawRadialGradient

but it draws circle. It will be good if you say me how to fill any shape by radial gradient. Thanks

Antigluk
  • 1,176
  • 2
  • 11
  • 30

1 Answers1

16

Add a path to current context that defines the desired shape and clip the context before drawing. Sample code:

- (void)drawRect:(CGRect)rect
{
    CGPoint c = self.center ;
    // Drawing code
    CGContextRef cx = UIGraphicsGetCurrentContext();

    CGContextSaveGState(cx);
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

    CGFloat comps[] = {1.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0};
    CGFloat locs[] = {0,1};
    CGGradientRef g = CGGradientCreateWithColorComponents(space, comps, locs, 2);


    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, c.x, c.y);
    CGPathAddLineToPoint(path, NULL, c.x, c.y-100);
    CGPathAddArcToPoint(path, NULL, c.x+100, c.y-100, c.x+100, c.y, 100);
    CGPathAddLineToPoint(path, NULL, c.x, c.y);

    CGContextAddPath(cx, path);
    CGContextClip(cx);

    CGContextDrawRadialGradient(cx, g, c, 1.0f, c, 320.0f, 0);

    CGContextRestoreGState(cx);   
    ... // Do some more drawing may be
}
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Hi Vladimar, such a great drawing this is. – Anton Unt Nov 26 '12 at 13:01
  • Hi Vladimar, such a great drawing this is. I need help with drawing a similar gradient but within a rectangle. I have a rectangular area that's black and I need a gray color to originate radially from the centre of the UIView. I'll really appreciate your help. – Anton Unt Nov 26 '12 at 13:07
  • @Shukaku, I'm not sure but won't just clipping to your rectangular region work? – Vladimir Nov 26 '12 at 13:39
  • It will and it did. It was stupid of me to ask the question. Thanks a lot for the reply! – Anton Unt Nov 26 '12 at 14:47
  • If you have sometime, would you please take a look at this: http://stackoverflow.com/questions/13567733/how-to-draw-on-two-separate-layers-ios-coregraphics – Anton Unt Nov 26 '12 at 15:18
  • This is confusing code. Why are there so many hard-coded numbers? Shouldn't the gradient be the same size as its frame? – zakdances May 09 '13 at 04:49
  • @Vladimir it looks like you need to release some of your objects (ColorSpace, Gradient, Path). – tjf Jun 23 '14 at 14:08