iosswiftswift4.2image-rendering

UIView to UIImage using UIGraphicsImageRenderer wrongly renderer image with alpha


I'm converting a UIView to UIImage, to set it as navigationBar background.

Thats view has an gradient layer, and when i use setBackgroundImage(_ backgroundImage: UIImage?, for barMetrics: UIBarMetrics) using the converted view, navigation gets a little transparent, something like 0.8 alpha

Here's the code that i'm using:

let navBackground = UIView(frame: CGRect(x: UIApplication.shared.statusBarFrame.origin.x, 
                                             y: UIApplication.shared.statusBarFrame.origin.y, 
                                             width: UIApplication.shared.statusBarFrame.width, 
                                             height: UIApplication.shared.statusBarFrame.height+self.navigationController!.navigationBar.frame.size.height))
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor(red:0.16, green:0.22, blue:0.49, alpha:1.0).cgColor, UIColor(red:0.31, green:0.53, blue:0.78, alpha:1.0).cgColor]
gradient.locations = [0.0, 1.0]
gradient.startPoint = CGPoint(x: 0, y: 1)
gradient.endPoint = CGPoint(x: 1, y: 0)
gradient.frame = navBackground.bounds
navBackground.layer.insertSublayer(gradient, above: nil)
let imgBackground = navBackground.asImage()
            self.navigationController?.navigationBar.setBackgroundImage(imgBackground, for: UIBarMetrics.default)

asImage() it's a UIView extension that convert UIView to UIImage:

extension UIView {

func asImage() -> UIImage {

    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        layer.render(in: rendererContext.cgContext)
    }

}!

Result: sample


Solution

  • Turn off the translucent property of navigation bar. Actually the default navigation background has a blur effect but your converted image has none.