使用UIGraphicsImageRenderer的UIView到UIImage会错误地渲染带有alpha

时间:2018-11-14 17:03:25

标签: ios swift swift4.2 image-rendering

我正在将UIView转换为UIImage,以将其设置为navigationBar背景。

该视图具有渐变层,当我使用转换后的视图使用setBackgroundImage(_ backgroundImage: UIImage?, for barMetrics: UIBarMetrics)时,导航会变得有点透明,例如0.8 alpha

这是我正在使用的代码:

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()是将UIView转换为UIImage的UIView扩展:

extension UIView {

func asImage() -> UIImage {

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

}!

结果:sample

1 个答案:

答案 0 :(得分:3)

关闭导航栏的translucent属性。实际上,默认的导航背景具有模糊效果,但转换后的图像则没有。