我正在将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
答案 0 :(得分:3)
关闭导航栏的translucent
属性。实际上,默认的导航背景具有模糊效果,但转换后的图像则没有。