0

I want to create a gradient view with three colours in swift.

linear-gradient(to right, #232c63 10%,#1d6cc1 59%,#33bdd6 100%);

How to define colours with %.

First Colour with 10 %

Second Colour with 59 %

Third Colour with 100 %

Example:

enter image description here

Parth Patel
  • 915
  • 11
  • 33

3 Answers3

5

If you want to use hex colors, use extension like these: https://stackoverflow.com/a/24263296/4711785

After that you can use colorWithAlphaComponent instance method like above which is mentioned in official documentation

UIColor.black.withAlphaComponent(0.7)
Ahmet Sina Ustem
  • 1,090
  • 15
  • 32
3

Try using the locations array of CAGradientLayer to give the startPoint for each color in the gradient, i.e.

let gradient = CAGradientLayer()
gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor]
gradient.startPoint = .zero
gradient.endPoint = CGPoint(x: 1, y: 0)
gradient.locations = [0, 0.1, 0.59]
gradient.frame = view.bounds
view.layer.addSublayer(gradient)

In the above code, locations are calculated using the required percentage, i.e. 10%, 59%, 100%.

Also add the colors as per your requirement.

var locations: [NSNumber]? { get set }

An optional array of NSNumber objects defining the location of each gradient stop. Animatable.

The gradient stops are specified as values between 0 and 1. The values must be monotonically increasing. If nil, the stops are spread uniformly across the range. Defaults to nil.

PGDev
  • 23,751
  • 6
  • 34
  • 88
1

With this method you can choose the three colours you want:

func gradient(initialColor: UIColor, middleColor: UIColor,
              finalColor: UIColor) -> CAGradientLayer {
    let gradient = CAGradientLayer()
    gradient.frame = self.frame

    gradient.colors = [initialColor.withAlphaComponent(1.0), middleColor.withAlphaComponent(0.59), finalColor.withAlphaComponent(1.0)].map{$0.cgColor}
    gradient.locations = [0.29, 0.60, 1]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint (x: 1.0, y: 0.5)

    return gradient
}

It returns a CAGradientLayer that you can add directly into your view.

When using the "locations" parameter, you can choose where your colours are going to be displayed in terms of percentage. In my method they are: 0% (0 value), 50% (0.5 value) and 100% (1 value).

I recommend using that method inside a UIView extension as a best practice and reusable code in your app.

Parth Patel
  • 915
  • 11
  • 33
Jordi Gámez
  • 3,400
  • 3
  • 22
  • 35