如今 CAGradientLayer 已内置于 iOS。
就这么简单:
多年来,您只需这样做:
class GlowBall: UIView {
private lazy var pulse: CAGradientLayer = {
let l = CAGradientLayer()
l.type = .radial
l.colors = [ UIColor.red.cgColor,
UIColor.yellow.cgColor,
UIColor.green.cgColor,
UIColor.blue.cgColor]
l.locations = [ 0, 0.3, 0.7, 1 ]
l.startPoint = CGPoint(x: 0.5, y: 0.5)
l.endPoint = CGPoint(x: 1, y: 1)
layer.addSublayer(l)
return l
}()
override func layoutSubviews() {
super.layoutSubviews()
pulse.frame = bounds
pulse.cornerRadius = bounds.width / 2.0
}
}
重点是:
l.colors = [ UIColor.red.cgColor,
UIColor.yellow.cgColor,
UIColor.green.cgColor,
UIColor.blue.cgColor]
l.locations = [ 0, 0.3, 0.7, 1 ]
请注意,您可以根据需要更改“拉伸”...
l.locations = [ 0, 0.1, 0.2, 1 ]
使用任何你喜欢的颜色
l.colors = [ UIColor.systemBlue.cgColor,
UIColor.systemPink.cgColor,
UIColor.systemBlue.cgColor,
UIColor.systemPink.cgColor,
UIColor.systemBlue.cgColor,
UIColor.systemPink.cgColor,
UIColor.systemBlue.cgColor,
UIColor.systemPink.cgColor]
l.locations = [ 0,0.1,0.2,0.3,0.4,0.5,0.6,1 ]
现在真的那么容易。
非常有用的技巧:
假设您想要黄色,在 0.6 处有一个蓝色带:
l.colors = [ UIColor.yellow.cgColor,
UIColor.blue.cgColor,
UIColor.yellow.cgColor]
l.locations = [ 0, 0.6, 1 ]
效果很好。
# yellow...
# blue...
# yellow...
但通常你会这样做:
# yellow...
# yellow...
# blue...
# yellow...
# yellow...
请注意,每端有两个黄色 ...
l.colors = [ UIColor.yellow.cgColor,
UIColor.yellow.cgColor,
UIColor.blue.cgColor,
UIColor.yellow.cgColor,
UIColor.yellow.cgColor]
通过这种方式,您可以控制“多宽”蓝色带的宽度:
在本例中:蓝色带将窄而锐利:
l.locations = [ 0, 0.58, 0.6, 0.68, 1 ]
在本例中,蓝色带将宽而柔和:
l.locations = [ 0, 0.5, 0.6, 0.7, 1 ]
这确实是控制渐变并获得所需外观的秘诀。
如何使用...
注意这是 - 非常简单 - 一个 UIView !!
class GlowBall: UIView { ...
就这样
-
在情节提要中,将 UIView 放置在您想要的位置
-
在故事板中,将类更改为“GlowBall”而不是 UIView
你已经完成了!