I have a UIView
which I want to have a radial gradient, and I\'m wondering how to go about doing this?
Here's Karlis' answer in Swift 3:
override func draw(_ rect: CGRect) {
// Setup view
let colors = [UIColor.white.cgColor, UIColor.black.cgColor] as CFArray
let locations = [ 0.0, 1.0 ] as [CGFloat]
let radius = min((self.bounds.size.height / 2), (self.bounds.size.width / 2))
let center = CGPoint.init(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
// Prepare a context and create a color space
let context = UIGraphicsGetCurrentContext()
context!.saveGState()
let colorSpace = CGColorSpaceCreateDeviceRGB()
// Create gradient object from our color space, color components and locations
let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors, locations: locations)
// Draw a gradient
context!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
context?.restoreGState()
}