开发者

How do I apply an opacity gradient on a UIView?

I would like my UIView to fade from 100% opacit开发者_如何学编程y to 0% opacity. Any thoughts on how I can do this?


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜