I have a UINavigationController
with prefersLargeTitles = true
I'd like to apply a background colour to my nav bar, with a gradient mask so the colour essentially fades to a darker version.
I have tried to create a UIView
apply the mask and render this. This however involves rendering the UIView
as a UIImage
and then as a UIColor
so I can set the barTintColor
.
This works when just rendering a UIView
but when setting it on the navigation bar, the behaviour is not as I would like.
I would like that gradient to fill the entire green area.
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationBar()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func hideNavigationBar() {
navigationController?.setNavigationBarHidden(true, animated: false)
}
func showNavigationBar() {
navigationController?.setNavigationBarHidden(false, animated: false)
}
private func configureNavigationBar() {
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.isTranslucent = false
navigationItem.title = "Home"
let v = BrandedHeader(frame: .zero)
v.frame = navigationController?.navigationBar.frame ?? .zero
navigationController?.navigationBar.barTintColor = UIColor(patternImage: v.asImage()!)
}
}
extension UIImage {
static func usingHex(_ hex: String) -> UIImage {
let color = UIColor.usingHex(hex)
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
extension UIView {
func asImage() -> UIImage? {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
} else {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
guard let currentContext = UIGraphicsGetCurrentContext() else {
return nil
}
self.layer.render(in: currentContext)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
}
class BrandedHeader: UIView {
let gradient: CAGradientLayer = CAGradientLayer()
override init (frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.green
gradient.frame = frame
gradient.colors = [UIColor.clear, UIColor.black.withAlphaComponent(0.3)].map { $0.cgColor }
gradient.locations = [0.0, 0.7]
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 1.0, y: 0.0)
layer.insertSublayer(gradient, at: 0)
}
required init?(coder aDecoder: NSCoder) {
return nil
}
override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = frame
gradient.removeAllAnimations()
}
}
See Question&Answers more detail:os