0

It should be very simple to create a black to white radial gradient using Core Graphics, but even after many tries I am not able to figure where I am going wrong.

I want something like this: enter image description here

This is my code:

CGFloat radius = shapeRect.size.width/2.0;
CGPoint center = CGPointMake(shapeRect.origin.x+shapeRect.size.width/2, shapeRect.origin.y+shapeRect.size.height/2);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(NULL, shapeRect.size.width, shapeRect.size.height, 8, shapeRect.size.width*4, colorSpace, kCGImageAlphaNone);
CGFloat components[] = {0.0,   1.0};
CGFloat locations[] = {0.0, 1.0};
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
CGContextDrawRadialGradient(context, gradient, center, 10, center, radius, 0);

CGImageRef img = CGBitmapContextCreateImage(context);
[maskedView setImage:[UIImage imageWithCGImage:img]];

CGGradientRelease(gradient);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

ShapeRect here has self.view bounds.

I am getting a whole black screen with no gradient as output. I am using iPhone 7 simulator.

Your suggestions can save my day

Thank you.

beyowulf
  • 15,101
  • 2
  • 34
  • 40
maven25
  • 231
  • 2
  • 12

1 Answers1

0

Please check this snippet. You can change components and locations values to get what you want and to understand how the drawing works. Refer to CGGradientCreateWithColorComponentsdescription

#import "TestView.h"

@implementation TestView {
    CGGradientRef _gradient;
}

-(void)drawRect:(CGRect)rect
{
    CGFloat radius = self.frame.size.width / 2.0;
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGGradientRef gradient = [self createGradient];
    CGContextDrawRadialGradient(context, gradient, center, 10, center, radius, kCGGradientDrawsBeforeStartLocation);
}

-(CGGradientRef)createGradient
{
    if (!_gradient) {
        CGFloat components[] = { 0.0, 1.0, 0.5, 0.5, 1.0, 0.3 };
        CGFloat locations[] = { 0.0, 0.6, 1.0 };
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
        _gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 3);
        CGColorSpaceRelease(colorSpace);
    }
    return _gradient;
}

- (void)layoutSubviews
{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.layer.borderWidth = 1.;
}


@end

Result:

enter image description here

schmidt9
  • 4,436
  • 1
  • 26
  • 32