Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a UIView have an effect of transparent gradient?

I want to make a UIView have an effect of transparent gradient from the middle to the left and right. Like in this example:

enter image description here

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.

like image 710
Desgard_Duan Avatar asked Apr 08 '16 02:04

Desgard_Duan


3 Answers

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 
like image 72
R. Mohan Avatar answered Sep 20 '22 08:09

R. Mohan


Screenshot

enter image description here

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 
like image 44
Leo Avatar answered Sep 19 '22 08:09

Leo


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.

like image 27
Kyokook Hwang Avatar answered Sep 20 '22 08:09

Kyokook Hwang