Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding fading color & transparency to UIView

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

like image 395
JAHelia Avatar asked Feb 13 '13 13:02

JAHelia


People also ask

How do you apply gradient fill?

Click the shape, and when the Format tab appears, click Shape Fill. Click Gradient > More Gradients > Gradient fill. Pick a Type from the list. To set the direction for the gradient, click Direction.


1 Answers

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.

like image 94
PedroSilva Avatar answered Nov 09 '22 00:11

PedroSilva