I have a UIView
which I want to have a radial gradient, and I'm wondering how to go about doing this?
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.
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)
}
}
On Storyboard, set the UIView to the above RadialGradientView
in Identity Inspector:
Set the Inside Color and Outside Color for your gradient in Attributes Inspector and see the change on your Storyboard:
(Note: I made the UIView on the Storyboard big enough to so it fills the entire