Gradient defined by trigonometric function in core graphics

221 views Asked by At

Apple has made it very simple to to make linear and radial gradients, but is it possible to have the color of the gradient be set by a definable function? In my situation I want to make the fill color of an object to vary with a sinus function along the x-axis. It is not hard to make pngs and use them as patterns instead, but I just wonder if it is possible to make gradients where the red, green and blue components vary along certain axis with a sinus function instead.

Any answer is appreciated. Thanks in advance.

1

There are 1 answers

0
hennes On

When you create the gradient using the CAGradientLayer class, you can use the colors property with a large number of colors and vary the color components according to the sine function. There will be linear interpolation between each pair of consecutive colors which will, however, not be noticeable when the number of colors (and locations) is large enough.

Here is an example that draws a sine gradient that variates back and forth between red and blue.

// Compute the colors using a sine step-size
let samples = 100
var colors = [CGColor]()
for i in 0..<samples {
    let component = CGFloat(0.5 + sin(Double(i) / Double(samples - 1) * 4.0 * M_PI) / 2.0)
    colors.append(UIColor(red: component, green: 0, blue: 1 - component, alpha: 1).CGColor)
}

// Create the gradient layer
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = colors

// Install the gradient layer        
gradientLayer.frame = self.view.bounds
self.view.layer.insertSublayer(gradientLayer, atIndex: 0)

The end result looks like this.

Xcode simulator screenshot