I'm trying to set a gradient colour background for my navigation bar. Code is like so:
extension UINavigationBar {
func setGradientBackground(to navController: UINavigationController) {
let gradient = CAGradientLayer()
var bounds = navController.navigationBar.bounds
bounds.size.height += UIApplication.shared.statusBarFrame.size.height
gradient.frame = bounds
gradient.colors = [UIColor.init(red: 85, green: 181, blue: 180, alpha: 1), UIColor.init(red: 76, green: 144, blue: 172, alpha: 1)]
gradient.startPoint = CGPoint(x: 0.5, y: 0)
gradient.endPoint = CGPoint(x: 0.5, y: 1)
if let image = getImageFrom(gradientLayer: gradient) {
navController.navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
}
}
And then make it an image:
func getImageFrom(gradientLayer:CAGradientLayer) -> UIImage? {
var gradientImage:UIImage?
UIGraphicsBeginImageContext(gradientLayer.frame.size)
if let context = UIGraphicsGetCurrentContext() {
gradientLayer.render(in: context)
gradientImage = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
}
UIGraphicsEndImageContext()
return gradientImage
}
viewDidLoad:
navigationController!.navigationBar.setGradientBackground(to: self.navigationController!)
But the result is not the colours I choose is only white. enter image description here Is anyone know what is going wrong ?