I want to make a UIView
have an effect of transparent gradient from the middle to the left and right. Like in this example:
The word 籍
has the desired effect. This view is achieved by the class MarqueeLabel. I examined the source code, it is likely implemented by class CALayer
.
In Swift 4: for top to bottom transparent gradient.
let gradient = CAGradientLayer() gradient.startPoint = CGPoint(x: 0.5, y: 0.0) gradient.endPoint = CGPoint(x: 0.5, y: 0.6) let whiteColor = UIColor.white gradient.colors = [whiteColor.withAlphaComponent(0.0).cgColor, whiteColor.withAlphaComponent(1.0).cgColor, whiteColor.withAlphaComponent(1.0).cgColor] gradient.locations = [NSNumber(value: 0.0),NSNumber(value: 0.2),NSNumber(value: 1.0)] gradient.frame = gradientView.bounds gradientView.layer.mask = gradient
Screenshot
Swift code
let mask = CAGradientLayer() mask.startPoint = CGPointMake(0.0, 0.5) mask.endPoint = CGPointMake(1.0, 0.5) let whiteColor = UIColor.whiteColor() mask.colors = [whiteColor.colorWithAlphaComponent(0.0).CGColor,whiteColor.colorWithAlphaComponent(1.0),whiteColor.colorWithAlphaComponent(1.0).CGColor] mask.locations = [NSNumber(double: 0.0),NSNumber(double: 0.2),NSNumber(double: 1.0)] mask.frame = label.bounds label.layer.mask = mask
You can use CAGradientLayer
as following.
gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = baseView.bounds;
gradientLayer.startPoint = CGPointMake(0.5,0.0);
gradientLayer.endPoint = CGPointMake(0.5,1.0);
gradientLayer.locations = @[@(0.0), @(0.2), @(1.0)];
gradientLayer.colors = @[(id)[UIColor colorWithWhite:1.0 alpha:0.9].CGColor,
(id)[UIColor colorWithWhite:1.0 alpha:0.3].CGColor,
(id)[UIColor colorWithWhite:1.0 alpha:0.0].CGColor];
[baseView.layer addSublayer:gradientLayer];
CAGradientLayer
supports several properties to make natural gradient, such as setting gradient direction by startPoint
and endPoint
, changing color curve by locations
and colors
.
You also make a transparent effect by using alpha channel of color.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With