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:
Step 3
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…