簡體   English   中英

UIView使用UIGraphicsImageRenderer錯誤地使用alpha渲染圖像

[英]UIView to UIImage using UIGraphicsImageRenderer wrongly renderer image with alpha

我正在將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)
    }

}!

結果: 樣本

關閉導航欄的translucent屬性。 實際上,默認導航背景具有模糊效果,但轉換后的圖像沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM