Episode #32

Core Graphics: Gradients

18 minutes
Published on September 6, 2012

This video is only available to subscribers. Get access to this video and 572 others.

Core Graphics is a complex topic, but can be very handy to create designs without using images, as well as maintaining resolution independence. In this episode I show how to create a couple of simple gradients using Core Graphics.

Episode Links

Drawing a Simple Linear Gradient

void drawLinearGradient(CGContextRef context, CGColorRef color1, CGColorRef color2, CGRect rect) {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };
    NSArray *colors = @[ (__bridge id)color1, (__bridge id)color2 ];

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

//  uncomment to see the rect outlined in yellow
//    CGContextSetStrokeColorWithColor(context, [[UIColor colorWithRed:1.0 green:1.0 blue:0 alpha:1.0] CGColor]);
//    CGContextSetLineWidth(context, 2);
//    CGContextStrokeRect(context, rect);

    CGContextSaveGState(context);

    CGContextAddRect(context, rect);
    CGContextClip(context);

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);

    CGContextRestoreGState(context);

    CFRelease(gradient);
    CFRelease(colorSpace);
}

Drawing a Glossy Gradient

void drawGlossyGradient(CGContextRef context, CGColorRef color1, CGColorRef color2, CGRect rect) {
    drawLinearGradient(context, color1, color2, rect);

    CGColorRef shineStartColor = [[UIColor colorWithWhite:1.0 alpha:0.65] CGColor];
    CGColorRef shineEndColor   = [[UIColor colorWithWhite:1.0 alpha:0.1] CGColor];

    CGRect shineRect = CGRectMake(CGRectGetMinX(rect),
                                  CGRectGetMinY(rect),
                                  CGRectGetWidth(rect),
                                  floorf(CGRectGetHeight(rect) / 2.0));

    drawLinearGradient(context, shineStartColor, shineEndColor, shineRect);
}

Calling this from drawRect

To do custom drawing, you must do it from a drawRect: method, inside of a custom view. To start, you'll need to obtain a reference to a CGContextRef in order to do your drawing:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();


}

Now you can simply call the helper methods above, passing in your context:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    drawLinearGradient(context, [[UIColor redColor] CGColor], [UIColor blueColor] CGColor], self.bounds);
}