Skip to content

Instantly share code, notes, and snippets.

@Jesse-calkin
Created July 13, 2016 21:14
Show Gist options
  • Save Jesse-calkin/49785d240feedd1451cb1f47069dce6a to your computer and use it in GitHub Desktop.
Save Jesse-calkin/49785d240feedd1451cb1f47069dce6a to your computer and use it in GitHub Desktop.
import UIKit
@IBDesignable public class GradientView: UIView {
// MARK: - Internal
@IBInspectable public var color1: UIColor = UIColor.magentaColor()
@IBInspectable public var color2: UIColor = UIColor.cyanColor()
@IBInspectable public var color3: UIColor = UIColor.clearColor()
@IBInspectable public var color4: UIColor = UIColor.clearColor()
@IBInspectable public var color5: UIColor = UIColor.clearColor()
@IBInspectable public var color6: UIColor = UIColor.clearColor()
@IBInspectable public var color7: UIColor = UIColor.clearColor()
@IBInspectable var location1: CGFloat = 0.0
@IBInspectable var location2: CGFloat = 1.0
@IBInspectable var location3: CGFloat = 1.0
@IBInspectable var location4: CGFloat = 1.0
@IBInspectable var location5: CGFloat = 1.0
@IBInspectable var location6: CGFloat = 1.0
@IBInspectable var location7: CGFloat = 1.0
// MARK: - Overrides
override public init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(gradientLayer)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.addSublayer(gradientLayer)
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
gradientLayer.colors = [color1.CGColor, color2.CGColor, color3.CGColor, color4.CGColor, color5.CGColor, color6.CGColor, color7.CGColor]
gradientLayer.locations = [location1, location2, location3, location4, location5, location6, location7]
gradientLayer.frame = frame
gradientLayer.bounds = bounds
}
// MARK: - Private
private let gradientLayer = CAGradientLayer()
private func updatePercentForLocation(location: CGPoint) {
location2 = min(1.0, max(0.0, location.y) / bounds.height)
setNeedsDisplay()
}
}
extension GradientView {
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
guard let location = touches.first?.locationInView(self) else { return }
updatePercentForLocation(location)
}
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
guard let location = touches.first?.locationInView(self) else { return }
updatePercentForLocation(location)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment