Skip to content

Instantly share code, notes, and snippets.

@ignatovSA
Last active March 3, 2018 04:50
Show Gist options
  • Save ignatovSA/ea7169afdc0a31f5d86ba9ca3350dc70 to your computer and use it in GitHub Desktop.
Save ignatovSA/ea7169afdc0a31f5d86ba9ca3350dc70 to your computer and use it in GitHub Desktop.
import UIKit
class LinearGradientLayer: CALayer {
public var colorSpace = CGColorSpaceCreateDeviceRGB()
public var colors: [CGColor]?
public var locations: [CGFloat]?
public var startPoint: CGPoint?
public var endPoint: CGPoint?
public var options: CGGradientDrawingOptions?
required override init() {
super.init()
needsDisplayOnBoundsChange = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(layer: Any) {
super.init(layer: layer)
}
override func draw(in ctx: CGContext) {
ctx.saveGState()
guard let colors = colors, let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors as CFArray, locations: locations) else { return }
ctx.drawLinearGradient(
gradient,
start: transformPoint(startPoint ?? CGPoint(x: 0.5, y: 0)),
end: transformPoint(endPoint ?? CGPoint(x: 0.5, y: 1)),
options: options ?? CGGradientDrawingOptions(rawValue: 0)
)
}
private func transformPoint(_ point: CGPoint) -> CGPoint {
return CGPoint(x: bounds.width * point.x, y: bounds.height * point.y)
}
}
let rectangularFrame = CGRect(x: 0, y:0, width: 750, height: 1334)
let colors = [UIColor.magenta.cgColor, UIColor.purple.cgColor, UIColor.cyan.cgColor]
let gradientViewCALayer = UIView(frame: rectangularFrame)
let gradientLayer = CAGradientLayer()
gradientLayer.frame = gradientViewCALayer.bounds
gradientLayer.colors = colors
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientViewCALayer.layer.addSublayer(gradientLayer)
let gradientViewLinearLayer = UIView(frame: rectangularFrame)
let linearGradient = LinearGradientLayer()
linearGradient.colors = colors
linearGradient.startPoint = CGPoint(x: 0.0, y: 0)
linearGradient.endPoint = CGPoint(x: 1.0, y: 1.0)
linearGradient.frame = gradientViewLinearLayer.bounds
gradientViewLinearLayer.layer.addSublayer(linearGradient)
gradientViewCALayer
gradientViewLinearLayer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment