How to gradient locations work in iOS?

Viewed 11349

I am working on a little project playing with colors in Xcode. Was wondering what the gradient locations do.

I noticed that gradientLayer.locations = [0.0, 1.0] will make it vertical, so i thought that gradientLayer.locations = [0.5, 0.5] would make it horizontal?

[0.5, 0.5] - results in 2 blocks of color stacked on top of each other, no gradient [0.0, 1.0] - results in gradient i am looking for, 2 vertical colors, with gradient

I know its kind of vague, but was looking for an explanation here. This doesnt make a lot of sense to me.

Thank,

Matt

2 Answers

This is quite an old answer, and coming across it I thought that I'd update the accepted answer for Swift.

    for view in stackView.arrangedSubviews {
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.black.cgColor
    }

    // 1
    var gradient: CAGradientLayer = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
    gradient.frame = view1.bounds
    gradient.locations = [0.0, 0.5]
    view1.layer.insertSublayer(gradient, at: 0)

    // 2
    gradient = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
    gradient.frame = view2.bounds
    gradient.locations = [0.5, 1.0]
    view2.layer.insertSublayer(gradient, at: 0)

    // 3
    gradient = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor]
    gradient.frame = view3.bounds
    gradient.locations = [0, 0.5, 1.0]
    view3.layer.insertSublayer(gradient, at: 0)

    // 4
    gradient = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor]
    gradient.frame = view4.bounds
    gradient.locations = [0, 0.8, 1.0]
    view4.layer.insertSublayer(gradient, at: 0)

I've backed this up with a GitHub link for anyone interested https://github.com/stevencurtis/Gradients

Related