Skip to content

Instantly share code, notes, and snippets.

@ianhirschfeld
Created October 3, 2014 06:19
Show Gist options
  • Save ianhirschfeld/106abafc9542797eceec to your computer and use it in GitHub Desktop.
Save ianhirschfeld/106abafc9542797eceec to your computer and use it in GitHub Desktop.
Example of using AngleGradientLayer to create an angle gradient border.
//
// AngleGradientBorderView.swift
// AngleGradientBorderTutorial
//
import UIKit
class AngleGradientBorderView: UIView {
// Constants
let DefaultGradientBorderColors: [AnyObject] = [
UIColor.redColor().CGColor,
UIColor.greenColor().CGColor,
UIColor.blueColor().CGColor,
UIColor.redColor().CGColor, // Repeat the first color to make a smooth transition
]
let DefaultGradientBorderWidth: CGFloat = 4
// Set the UIView's layer class to be our AngleGradientBorderLayer
override class func layerClass() -> AnyClass {
return AngleGradientBorderLayer.self
}
// Initializer
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupGradientLayer()
}
// Custom initializer
init(frame: CGRect, borderColors gradientBorderColors: [AnyObject]? = nil, borderWidth gradientBorderWidth: CGFloat? = nil) {
super.init(frame: frame)
setupGradientLayer(borderColors: gradientBorderColors, borderWidth: gradientBorderWidth)
}
// Setup the attributes of this view's layer
func setupGradientLayer(borderColors gradientBorderColors: [AnyObject]? = nil, borderWidth gradientBorderWidth: CGFloat? = nil) {
// Grab this UIView's layer and cast it as AngleGradientBorderLayer
let l: AngleGradientBorderLayer = self.layer as AngleGradientBorderLayer
// NOTE: Since our gradient layer is built as an image,
// we need to scale it to match the display of the device.
l.contentsScale = UIScreen.mainScreen().scale
// Set the gradient colors
if gradientBorderColors != nil {
l.colors = gradientBorderColors!
} else {
l.colors = DefaultGradientBorderColors
}
// Set the border width of the gradient
if gradientBorderWidth != nil {
l.gradientBorderWidth = gradientBorderWidth!
} else {
l.gradientBorderWidth = DefaultGradientBorderWidth
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment