adding fading color & transparency to UIView

JAHelia picture JAHelia · Feb 13, 2013 · Viewed 8.7k times · Source

I know how to create and animate a view like the one in the Share sub view of the new app store app that comes with iOS 6+ (see attached screenshot), but I don't know how to add that nice coloring effect with transparency on this view. anyone can provide a code sample to make a UIView looks exactly the one in the screenshot?

P.S. the alpha property alone of UIView does not do such thing.

enter image description here

Answer

PedroSilva picture PedroSilva · Feb 18, 2013

You can add this method to a UIView category and reuse as needed. It applies a linear black gradient from "theColor" to transparent to the given view.

You should have QuartzCore.framework in your project in order to use the CAGradientLayer object.

+ (void)addLinearGradientToView:(UIView *)theView withColor:(UIColor *)theColor transparentToOpaque:(BOOL)transparentToOpaque
{
    CAGradientLayer *gradient = [CAGradientLayer layer];

    //the gradient layer must be positioned at the origin of the view
    CGRect gradientFrame = theView.frame;
    gradientFrame.origin.x = 0;
    gradientFrame.origin.y = 0;
    gradient.frame = gradientFrame;

    //build the colors array for the gradient
    NSArray *colors = [NSArray arrayWithObjects:
                       (id)[theColor CGColor],
                       (id)[[theColor colorWithAlphaComponent:0.9f] CGColor],
                       (id)[[theColor colorWithAlphaComponent:0.6f] CGColor],
                       (id)[[theColor colorWithAlphaComponent:0.4f] CGColor],
                       (id)[[theColor colorWithAlphaComponent:0.3f] CGColor],
                       (id)[[theColor colorWithAlphaComponent:0.1f] CGColor],
                       (id)[[UIColor clearColor] CGColor],
                       nil];

    //reverse the color array if needed
    if(transparentToOpaque)
    {
       colors = [[colors reverseObjectEnumerator] allObjects];
    }

    //apply the colors and the gradient to the view
    gradient.colors = colors;

    [theView.layer insertSublayer:gradient atIndex:0];
}

Please note that you should have the backgroundColor of theView set to clearColor so that it doesn't interfere with the gradient. Also, for the results shown in the screenshot, the transparentToOpaque flag should be YES.