如何使UIView具有透明渐变的效果?

时间:2016-04-08 02:00:48

标签: ios swift uiview gradient

我想让UIView具有从中间到左右的透明渐变效果。就像在这个例子中一样:

enter image description here

单词具有所需的效果。该视图由类MarqueeLabel实现。我检查了源代码,它可能由类CALayer实现。

4 个答案:

答案 0 :(得分:11)

截图

enter image description here

Swift代码

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

答案 1 :(得分:9)

您可以使用以下CAGradientLayer

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支持多种属性来制作自然渐变,例如按startPointendPoint设置渐变方向,更改颜色曲线locationscolors

您还可以使用颜色的Alpha通道制作透明效果。

答案 2 :(得分:5)

斯威夫特3:

let mask = CAGradientLayer()
mask.startPoint = CGPoint(x: 0, y: 0.5)
mask.endPoint = CGPoint(x:1.0, y:0.5)
let whiteColor = UIColor.white
mask.colors = [whiteColor.withAlphaComponent(0.0).cgColor,whiteColor.withAlphaComponent(1.0),whiteColor.withAlphaComponent(1.0).cgColor]
mask.locations = [NSNumber(value: 0.0),NSNumber(value: 0.2),NSNumber(value: 1.0)]
mask.frame = view.bounds
view.layer.mask = mask

答案 3 :(得分:0)

使用清晰的颜色而不是设置alpha值。

let gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor]
gradientLayer.locations = [0, 0.2, 1]
gradientLayer.frame = gradientView.bounds
gradientView.layer.mask = gradientLayer