我创建了具有三种颜色的CAGradientLayer
,我需要为每种颜色指定不同的位置。
例子:
Red = 0 to 50 %
Yellow = 51 to 80 %
Green = 81 to 100 %
我尝试提供
startPoint
和endPoint
,但是没有用。 最佳答案
如果将以下代码放到Playground中,您将获得所需的确切输出:
let view = UIView(frame: CGRectMake(0,0,200,100))
let layer = CAGradientLayer()
layer.frame = view.frame
layer.colors = [UIColor.greenColor().CGColor, UIColor.yellowColor().CGColor, UIColor.redColor().CGColor]
layer.locations = [0.0, 0.8, 1.0]
view.layer.addSublayer(layer)
XCPShowView("ident", view: view)
输出:
您只需将颜色定义为
CGColors
数组和相同大小的NSNumber
数组即可,每个数组的值都在0.0到1.0之间。不要为此使用
startPoint
和endPoint
-它们用于定义渐变在何处显示图层的位置-与百分比和颜色等没有任何关系。较新的Swift3版本的代码:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
let layer = CAGradientLayer()
layer.frame = view.frame
layer.colors = [UIColor.green.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
layer.locations = [0.0, 0.8, 1.0]
view.layer.addSublayer(layer)
PlaygroundPage.current.liveView = view
关于ios - 如何将 “locations”赋予CAGradientLayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34390492/