Skip to content

Instantly share code, notes, and snippets.

@abhi21git
Created November 1, 2022 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhi21git/e1ba298a7235f3fde798f265ad7bf3ba to your computer and use it in GitHub Desktop.
Save abhi21git/e1ba298a7235f3fde798f265ad7bf3ba to your computer and use it in GitHub Desktop.
Create gradients and cache them to reduce memory footprint.
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