如何为iOS导航栏创建水平渐变背景? [英] How can I create a horizontal gradient background for my iOS nav bar?
问题描述
我知道如何设置导航栏背景颜色(使用barTintColor),但现在我正在开发一个需要水平渐变(不是典型的垂直渐变)的iOS应用。
I know how to set a navigation bar background color (with barTintColor), but now I am working on an iOS app that calls for a horizontal gradient (not the typical vertical gradient).
如何创建具有水平渐变背景的导航栏?
How can I create a navigation bar with a horizontal gradient background?
推荐答案
如果要以编程方式设置给定UINavigationBar的梯度我有一个解决方案。
If you want to programmatically set the gradient of a given UINavigationBar I have a solution for you.
首先使用您想要的颜色和位置设置 CAGradientLayer
。
First setup a CAGradientLayer
with your desired colors and locations.
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = navigationBar.bounds;
gradientLayer.colors = @[ (__bridge id)[UIColor greenColor].CGColor,
(__bridge id)[UIColor blueColor].CGColor ];
gradientLayer.startPoint = CGPointMake(0.0, 0.5);
gradientLayer.endPoint = CGPointMake(1.0, 0.5);
然后抓住该图层的UImage。
Then grab the UImage for that layer.
UIGraphicsBeginImageContext(gradientLayer.bounds.size);
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
将 gradientImage
设置为您的backgroundImage UINavigationBar
。
Set the gradientImage
as the backgroundImage for your UINavigationBar
.
[navigationBar setBackgroundImage:gradientImage forBarMetrics:UIBarMetricsDefault];
Swift解决方案:
Swift Solution:
[![// Setup the gradient
let gradientLayer = CAGradientLayer()
gradientLayer.frame = navigationBar.bounds
gradientLayer.colors = [UIColor.green.cgColor, UIColor.blue.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
// Render the gradient to UIImage
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Set the UIImage as background property
navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
这篇关于如何为iOS导航栏创建水平渐变背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!