blancos blancos - 1 year ago 283
Objective-C Question

How to draw radial gradients in a CALayer?

I know

doesn't support radial gradient at the moment and only has option of

I want something like below:

enter image description here

I have looked around for this issue and found that there is a way around this. But the explanations were not clear to me. So I want to know if I can draw radial gradients using
and if so, then how to do it?

Answer Source

From what I understood, you just need a layer that draws a gradient, and CGContextDrawRadialGradient works perfectly for that need. And to reiterate on what you said, CAGradientLayer doesn't support radial gradients, and nothing we can do about that, except unnecessary swizzling that can be done cleanly with a CALayer subclass.

(note: the gradient drawing code was taken from here. It isn't what this answer is about.)


GradientLayer *gradientLayer = [GradientLayer new];
gradientLayer.frame = self.view.bounds;

[self.view.layer addSublayer:gradientLayer];

CALayer subclass:

- (instancetype)init
    self = [super init];
    if (self) {
        [self setNeedsDisplay];
    return self;

- (void)drawInContext:(CGContextRef)ctx

    size_t gradLocationsNum = 2;
    CGFloat gradLocations[2] = {0.0f, 1.0f};
    CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.5f};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);

    CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;

    CGContextDrawRadialGradient (ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);


enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download