Last active
March 3, 2018 04:50
-
-
Save ignatovSA/ea7169afdc0a31f5d86ba9ca3350dc70 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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