Search code examples
iosswiftuikitgradient

Gradient mask on UIView


I have a UIView and want to have the bottom part of it fade out to 0 opacity.

May this be done to a UIView (CALayer) in order to affect an entire UIView and its content?


Solution

  • Yes, you can do that by setting CAGradientLayer as your view's layer mask:

    #import <QuartzCore/QuartzCore.h>
    
    ...
    
    CAGradientLayer *maskLayer = [CAGradientLayer layer];
    
    maskLayer.frame = view.bounds;
    maskLayer.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor];
    maskLayer.startPoint = CGPointMake(0.5, 0);
    maskLayer.endPoint = CGPointMake(0.5, 1.0);
    
    view.layer.mask = maskLayer;
    

    P.S. You also need to link QuartzCore.framework to your app to make things work.