Sidwyn Koh
Sidwyn Koh

Reputation: 1742

How do I apply an opacity gradient on a UIView?

I would like my UIView to fade from 100% opacity to 0% opacity. Any thoughts on how I can do this?

Upvotes: 2

Views: 2676

Answers (2)

Stephen Furlani
Stephen Furlani

Reputation: 6856

Ray Wenderlich has a great tutorial on setting gradients for objects. My suggestion is to modify the following code to suit your needs.

//Ray's code:
void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, 
    CGColorRef  endColor) {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };

    NSArray *colors = [NSArray arrayWithObjects:(id)startColor, (id)endColor, nil];

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

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

    CGContextSaveGState(context);
    CGContextAddRect(context, rect);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

Upvotes: 3

BoltClock
BoltClock

Reputation: 723468

If the view, together with its labels, is sitting on some static background image or color, a quick and dirty trick is to create gradient PNGs of that image or color and place them over the view.

Otherwise, see if you can adapt this CALayer gradient mask solution for your view.

Upvotes: 1

Related Questions