我想在UINavigationBar
中添加渐变色。水平渐变的代码完美地工作,但对于垂直渐变,它没有显示正确的颜色。
Thanx提前!!!
我的当前垂直渐变代码:
extension UINavigationBar {
/// Applies a background gradient with the given colors
func applyNavigationGradient( colors : [UIColor]) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.colors = colors.map { $0.cgColor }
// *** for horizontal gradient ***
// gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
// gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
// *** for vertical gradient ***
// gradientLayer.locations = [0,1]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
setBackgroundImage(image, for: UIBarMetrics.default)
}
}
答案 0 :(得分:1)
swift 4.1的工作代码。只需将以下视图载入:
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let gradientLayer = CAGradientLayer()
var updatedFrame = self.navigationController!.navigationBar.bounds
updatedFrame.size.height += 20
gradientLayer.frame = updatedFrame
gradientLayer.colors = [UIColor.green.cgColor, UIColor.blue.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0) // vertical gradient start
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0) // vertical gradient end
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.navigationController!.navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
}