Create Designable Subclass of UIView To Create Gradient Layer on Draw View

Source Code

// MARK: – Designable GradientView Class
@IBDesignable final class GradientView: UIView {

@IBInspectable var startColor: UIColor = UIColor.init(colorLiteralRed: 158.0/255.0, green: 201.0/255.0, blue: 250.0/255.0, alpha: 1.0)
@IBInspectable var endColor: UIColor = UIColor.white

/* Initiate the view with Radial Gradient filled with defined colors */
override func draw(_ rect: CGRect) {

// Setup view
let colors = [endColor.cgColor, startColor.cgColor] as CFArray
let locations = [ 0.0, 1.0 ] as [CGFloat]
let radius = min((self.bounds.size.height + 50), (self.bounds.size.width + 50))
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()
}

}

Use

Advertisements
Create Designable Subclass of UIView To Create Gradient Layer on Draw View

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s