Skip to content

Instantly share code, notes, and snippets.

@AashirMubeeb
Created December 5, 2022 07:24
Show Gist options
  • Save AashirMubeeb/454bd5feea393b066d2cd2bec19eaf24 to your computer and use it in GitHub Desktop.
Save AashirMubeeb/454bd5feea393b066d2cd2bec19eaf24 to your computer and use it in GitHub Desktop.
Draws Linear Gradient and designable from storyboard.
import Foundation
import Cocoa
// MARK: - Abstract
/// Draws Linear Gradient and designable from storyboard.
class DesignableGradientView: NSView {
@IBInspectable var isDrawGradient: Bool = false {
didSet {
reDrawGradient()
}
}
@IBInspectable open var startColor: NSColor = .init(red: 0.86, green: 0.25, blue: 0.59, alpha: 1) {
didSet {
reDrawGradient()
}
}
@IBInspectable open var endColor: NSColor = .init(red: 0.11, green: 0.14, blue: 0.46, alpha: 0.86) {
didSet {
reDrawGradient()
}
}
@IBInspectable open var rotation: CGFloat = 45.0 {
didSet{
reDrawGradient()
}
}
@IBInspectable open var startPosition: CGFloat = .zero {
didSet{
reDrawGradient()
}
}
@IBInspectable open var endPosition: CGFloat = 1.0 {
didSet{
reDrawGradient()
}
}
override open func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard isDrawGradient else {
return
}
let bgGradient = NSGradient.init(colorsAndLocations: (startColor, startPosition), (endColor, endPosition))
bgGradient?.draw(in: dirtyRect, angle: rotation)
}
func reDrawGradient() {
needsDisplay = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment