How can I set the UINavigationbar with gradient color?

前端 未结 11 725
花落未央
花落未央 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:16

    Create gradient layer and add it as background of navigation bar.

        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = self.navigationController.navigationBar.bounds;
        gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
        [self.navigationController.navigationBar setBackgroundImage:[self imageFromLayer:gradient] forBarMetrics:UIBarMetricsDefault];
    

    For creating image from layer.

    - (UIImage *)imageFromLayer:(CALayer *)layer
    {
        UIGraphicsBeginImageContext([layer frame].size);
    
        [layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        return outputImage;
    }
    

    One more thing, there is one library available in github : CRGradientNavigationBar you can also use this library.

提交回复
热议问题