How do I add a radial gradient to a UIView?

后端 未结 5 1842
你的背包
你的背包 2020-12-14 21:12

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

5条回答
  •  一整个雨季
    2020-12-14 21:30

    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()
    }
    

提交回复
热议问题