How can I set the UINavigationbar with gradient color?

前端 未结 11 712
花落未央
花落未央 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条回答
  •  一向
    一向 (楼主)
    2020-11-30 23:17

    In Swift 3, Swift 4 and Swift 5:

    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)
    

    For creating image from layer:

    func image(fromLayer layer: CALayer) -> UIImage {
        UIGraphicsBeginImageContext(layer.frame.size)
    
        layer.render(in: UIGraphicsGetCurrentContext()!)
    
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return outputImage!
    }
    

    In Swift 2:

    let gradient = CAGradientLayer()
    let sizeLength = UIScreen.mainScreen().bounds.size.height * 2
    let defaultNavigationBarFrame = CGRectMake(0, 0, sizeLength, 64)
    
    gradient.frame = defaultNavigationBarFrame
    
    gradient.colors = [UIColor.whiteColor().CGColor, UIColor.blackColor().CGColor]
    
    UINavigationBar.appearance().setBackgroundImage(self.image(fromLayer: gradient), forBarMetrics: .Default)
    

    For creating image from layer:

    func image(fromLayer layer: CALayer) -> UIImage {    
        UIGraphicsBeginImageContext(layer.frame.size)
    
        layer.renderInContext(UIGraphicsGetCurrentContext()!)
    
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    
         UIGraphicsEndImageContext()
    
        return outputImage!
    }
    

提交回复
热议问题