atkabai
atkabai

Reputation: 31

Modern technique of adding gradient to UIView

I know of several ways of adding background gradients to UIView. I was wondering what is the most efficient and scalable way of doing so, and why? Here are the techniques I've used:

So what is most efficient and scalable way to add gradient as a background?

Upvotes: 3

Views: 7266

Answers (2)

jverrijt
jverrijt

Reputation: 696

As Fogmeister suggested above, do it in the drawRect: method of your UIView subclass.

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

    NSArray *gradientColors = [NSArray arrayWithObjects:(id) [UIColor redColor].CGColor, [UIColor yellowColor].CGColor, nil];

    CGFloat gradientLocations[] = {0, 0.50, 1};
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) gradientColors, gradientLocations);

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

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

Upvotes: 9

Peteee24
Peteee24

Reputation: 530

DrawRect is the more efficient way i think. I'd like to extend jverrijt's nice answer. If you need alpha components (transparent to black gradient f.e.), then you can use this:

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
CGContextSaveGState(UIGraphicsGetCurrentContext());
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
CGContextRestoreGState(UIGraphicsGetCurrentContext());

//Draw stuffs

UIGraphicsEndImageContext();

Upvotes: 0

Related Questions