Search code examples
iosquartz-2d

Quartz2d gradient fill an oval


I have a simple drawing routine that allows the user to draw two enclosed ovals on the screen. I want to fill the ovals with a gradient, using the inner oval to represent the "percentage" of the gradient. i.e. Th gradient will smoothly transition between the outside oval to the inside oval.

I have the interactive drawing working fine, now I just need to fill with the gradient.

Any thoughts? The docs only talk about perfectly circular gradients, not ovals.

enter image description here

_mike


Solution

  • I do not know whether it is possible oval gradient . But you can transform circle to oval. The idea is to draw a circle in transformed coordinate system.

    Sample of code:

    - (void)drawRect:(CGRect)rect
    {
       CGContextRef context = UIGraphicsGetCurrentContext();
       CGContextSaveGState(context);
       CGContextScaleCTM(context, 1.0, 0.5);
       CGGradientRef gradient;
       CGColorSpaceRef colorspace;
       CGFloat locations[2] = { 0.0, 1.0};
       NSArray *colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blueColor].CGColor];
       colorspace = CGColorSpaceCreateDeviceRGB();
       gradient = CGGradientCreateWithColors(colorspace, (CFArrayRef)colors, locations);
       CGPoint startPoint, endPoint;
       CGFloat startRadius, endRadius;
       startPoint.x = 180;
       startPoint.y = 180;
       endPoint.x = 180;
       endPoint.y = 180;
       startRadius = 0;
       endRadius = 100;
       CGContextDrawRadialGradient (context, gradient, startPoint, startRadius, endPoint, endRadius, 0);
       CGContextRestoreGState(context);
    }
    

    Result of running code:

    Result of running code: