20

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.enter image description here

luk2302
  • 55,258
  • 23
  • 97
  • 137
Sunil Rao
  • 800
  • 2
  • 6
  • 23
  • where exactly are you struggling? The layer has two properties `colors` and `locations` that should be of use for you. What language btw? – luk2302 Dec 21 '15 at 07:58
  • Your "example" is not clear, explain what exactly 0%-50%, 51%-80% and 81%-100% mean and add the code you used so that someone could show you the problem, otherwise all we can do is to quote documentation. – A-Live Dec 21 '15 at 08:22
  • The color on the gradient layer should be such and such percentage, by default all three colors will distribute evenly which I want to change. I am using Objective-C. Thank you. – Sunil Rao Dec 21 '15 at 09:09
  • It would be great if someone explains how "location" property of CAGradientLayer works for three or more colors. – Sunil Rao Dec 21 '15 at 09:57
  • @SunilRao I wrote an answer using your exact percentages. – luk2302 Dec 21 '15 at 10:43

1 Answers1

33

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:

enter image description here

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
luk2302
  • 55,258
  • 23
  • 97
  • 137