How do I add a radial gradient to a UIView?

Andrew picture Andrew · Nov 14, 2011 · Viewed 24k times · Source

I have a UIView which I want to have a radial gradient, and I'm wondering how to go about doing this?

Answer

Mark Moeykens picture Mark Moeykens · Jan 9, 2017

Swift 3 - @IBDesignable

I worked off Karlis and Alexander's answers. I aimed to simplify as much as possible. Such as removing color space and locations (nil) so the gradient uses the defaults.

How to Use

Step 1

Create file and add this code: import UIKit

@IBDesignable
class RadialGradientView: UIView {

    @IBInspectable var InsideColor: UIColor = UIColor.clear
    @IBInspectable var OutsideColor: UIColor = UIColor.clear

    override func draw(_ rect: CGRect) {
        let colors = [InsideColor.cgColor, OutsideColor.cgColor] as CFArray
        let endRadius = min(frame.width, frame.height) / 2
        let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
        let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
        UIGraphicsGetCurrentContext()!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
    }
}

Step 2

On Storyboard, set the UIView to the above RadialGradientView in Identity Inspector: Custom Class

Step 3

Set the Inside Color and Outside Color for your gradient in Attributes Inspector and see the change on your Storyboard: Radial Gradient

(Note: I made the UIView on the Storyboard big enough to so it fills the entire