How to fill a CAShapeLayer with an angled gradient
<p>How do I fill a <code>CAShapeLayer()</code> with a gradient and on an angle of 45 degrees?</p>

<p>For example, in <strong>Image 1</strong>, the below code draws a square and fills the layer blue (<code>UIColor.blueColor().CGColor</code>).</p>

<p>But, how do I fill it with a gradient on a 45 degree angle from blue to red like in <strong>Image 2</strong> (i.e. <code>UIColor.blueColor().CGColor</code> to <code>UIColor.redColor().CGColor</code>)?</p>

<p><strong>Code:</strong></p>

<pre><code>let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 100))
path.addLineToPoint(CGPoint(x: 100, y: 100))
path.addLineToPoint(CGPoint(x: 100, y: 0))
path.closePath()

let shape = CAShapeLayer()
shape.path = path.CGPath
shape.fillColor = UIColor.blueColor().CGColor
</code></pre>

<p><a href="https://i.stack.imgur.com/otWcv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/otWcv.png" alt="Solid-color square next to square with gradient"></a></p>