为UINavigationBar设置背景颜色是很常见的需求,一般设置导航栏背景颜色操作如下,直接设置barTintColor即可。
navigationController?.navigationBar.barTintColor = UIColor.red
效果如下:
我们也可以通过设置导航栏的背景图片来设置背景颜色,可以达到相同的效果:
navigationController?.navigationBar.setBackgroundImage(UIImage(named: "background"),
for: .default)
如果想要设置渐变的颜色,那么如何操作呢?思路也简单,获取渐变颜色,那么需要使用CAGradientLayer,但是为layer设置来渐变之后,如何设置呢?其实就是通过绘制layer得到对应的image,然后通过image设置导航栏的背景图片。具体操作如下,设置红白的渐变颜色:
let gradient = CAGradientLayer()
let sizeLength = UIScreen.main.bounds.size.width
let frameAndStatusBar = CGRect(x: 0, y: 0, width: sizeLength, height: 64)
gradient.frame = frameAndStatusBar
gradient.colors = [UIColor.white.cgColor, UIColor.red.cgColor]
navigationController?.navigationBar.setBackgroundImage(self.image(fromLayer: gradient), for: .default)
绘制方法:
func image(fromLayer layer: CALayer) -> UIImage {
UIGraphicsBeginImageContext(layer.frame.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage!
}
效果如下:
当然,为了方便直接设置导航栏背景变渐,我们可以使用扩展,具体实现如下:
extension UINavigationBar{
/// Applies a background gradient with the given colors
func apply(gradient colors : [UIColor]) {
var frameAndStatusBar: CGRect = self.bounds
frameAndStatusBar.size.height += 20 // add 20 to account for the status bar
setBackgroundImage(UINavigationBar.gradient(size: frameAndStatusBar.size, colors: colors), for: .default)
}
/// Creates a gradient image with the given settings
static func gradient(size : CGSize, colors : [UIColor]) -> UIImage? {
// Turn the colors into CGColors
let cgcolors = colors.map { $0.cgColor }
// Begin the graphics context
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
// If no context was retrieved, then it failed
guard let context = UIGraphicsGetCurrentContext() else { return nil }
// From now on, the context gets ended if any return happens
defer { UIGraphicsEndImageContext() }
// Create the Coregraphics gradient
var locations : [CGFloat] = [0.0, 1.0]
guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: cgcolors as NSArray as CFArray, locations: &locations) else { return nil }
// Draw the gradient
context.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: 0.0), end: CGPoint(x: size.width, y: 0.0), options: [])
// Generate the image (the defer takes care of closing the context)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
需要设置变渐方向,可以自己设置locations属性,现在使用非常简单:
navigationController?.navigationBar.apply(gradient: [UIColor.white, UIColor.red])
效果如下:
参考:
How can I set the UINavigationbar with gradient color?