gpt4 book ai didi

ios - 使用 UIGraphicsImageRenderer 的 UIView 到 UIImage 错误地使用 alpha 渲染图像

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:45 25 4
gpt4 key购买 nike

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

那个 View 有一个渐变层,当我使用 setBackgroundImage(_ backgroundImage: UIImage?, for barMetrics: UIBarMetrics) 使用转换后的 View 时,导航变得有点透明,比如 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

最佳答案

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

关于ios - 使用 UIGraphicsImageRenderer 的 UIView 到 UIImage 错误地使用 alpha 渲染图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53305348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com