How to give “locations” to CAGradientLayer

允我心安 提交于 2019-12-31 12:53:33

问题


I have created CAGradientLayer having three colors, i need to give each color different locations. Example:

Red = 0 to 50 %
Yellow = 51 to 80 %
Green = 81 to 100 %

I have tried with giving startPoint and endPoint but it did not work.


回答1:


If you put the following code into a Playground you will get the exact desired output:

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)

Outputting:

You simply define the colors as an array of CGColors, and an array of the same size of NSNumbers each between 0.0 and 1.0.

Dont use startPoint and endPoint for that - they are for defining from where to where the gradient is shown in the layer - it does not have anything to do with the percents and the colors etc.


More recent Swift3 version of the code:

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


来源:https://stackoverflow.com/questions/34390492/how-to-give-locations-to-cagradientlayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!