我已经研究了很多有关如何在iOS的NavigationBar中添加渐变的方法,但是并没有显示我的需要。我想要2种颜色渐变,顶部为白色,底部为透明。像这样 :
尝试使用CAGradientLayer
和CRGradientNavigationBar,
但是我尝试过的所有操作始终在顶部显示白色,但是当我将底部颜色设置为“透明”时,它显示出奇怪的黑色半透明颜色。
如何实现上图所示的类似NavigationBar?
谢谢!
最佳答案
创建渐变层并将其添加为导航栏的背景。
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];
用于从图层创建图像。
(UIImage *)imageFromLayer:(CALayer *)layer
{
UIGraphicsBeginImageContext([layer frame].size);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
还有一件事,github中提供了一个库:CRGradientNavigationBar您也可以使用此库。
关于ios - 如何在导航栏中添加渐变-iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47473336/