Created
November 1, 2022 07:52
-
-
Save abhi21git/e1ba298a7235f3fde798f265ad7bf3ba to your computer and use it in GitHub Desktop.
Create gradients and cache them to reduce memory footprint.
This file contains hidden or 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
class GradientView: UIImageView { | |
var gradientColors: [CGColor] = [UIColor.greyishBrown.withAlphaComponent(0.2).cgColor, UIColor.greyishBrown.cgColor] | |
var locations: [CGFloat]? = [0.0, 1.0] | |
override func layoutSubviews() { | |
self.contentMode = .scaleToFill | |
self.backgroundColor = .hotPink | |
self.image = drawGradientColor(in: self.bounds, colors: gradientColors) | |
} | |
func drawGradientColor(in rect: CGRect, colors: [CGColor]) -> UIImage? { | |
let currentContext = UIGraphicsGetCurrentContext() | |
currentContext?.saveGState() | |
defer { currentContext?.restoreGState() } | |
let size = rect.size | |
UIGraphicsBeginImageContextWithOptions(size, false, 0) | |
guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), | |
colors: colors as CFArray, | |
locations: locations) else { return nil } | |
let context = UIGraphicsGetCurrentContext() | |
context?.drawLinearGradient(gradient, | |
start: CGPoint.zero, | |
end: CGPoint(x: size.width, y: 0), | |
options: []) | |
let gradientImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return gradientImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment