How can I set the UINavigationbar with gradient color?

前端 未结 11 715
花落未央
花落未央 2020-11-30 22:27

I want to set the UINavigationbar backgroundColor to a gradient color where I would like to set it via an array of colors to create a Gradient, ide

11条回答
  •  Happy的楠姐
    2020-11-30 23:24

    In Swift 3

    let gradient = CAGradientLayer()
    let sizeLength = UIScreen.main.bounds.size.height * 2
    let defaultNavigationBarFrame = CGRect(x: 0, y: 0, width: sizeLength, height: 64)
    gradient.frame = defaultNavigationBarFrame
    gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
    UINavigationBar.appearance().setBackgroundImage(self.image(fromLayer: gradient), for: .default)
    
    func image(fromLayer layer: CALayer) -> UIImage {
        UIGraphicsBeginImageContext(layer.frame.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return outputImage!
    }
    

提交回复
热议问题