我使用下面的代码创建渐变,并借助图层中的功能图像将其设置为导航栏。
func image(fromLayer layer: CALayer) -> UIImage {
UIGraphicsBeginImageContext(layer.frame.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage!
}
//navbar
let gradient = CAGradientLayer()
let cornerRadiusOfNavBar : CGFloat! = 0
if #available(iOS 10.0, *) {
gradient.colors = [Constants.Colors.violet.cgColor , Constants.Colors.green.cgColor ]
}
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = self.navigationController!.navigationBar.bounds
gradient.cornerRadius = cornerRadiusOfNavBar
navigationItem.title = NSLocalizedString("Register", comment: "")
self.navigationController!.navigationBar.setBackgroundImage(self.image(fromLayer: gradient), for: .default)
我在导航栏下面有一个堆栈视图,我使用此代码为它设置渐变:
//stackview
let gradientView = CAGradientLayer()
let cornerRadiusOfStackView : CGFloat! = 0
if #available(iOS 10.0, *) {
gradientView.colors = [Constants.Colors.violet.cgColor , Constants.Colors.green.cgColor ]
}
gradientView.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientView.endPoint = CGPoint(x: 1.0, y: 0.5)
gradientView.frame = self.stackViewHoldingButtons.bounds
gradientView.cornerRadius = cornerRadiusOfStackView
self.stackViewHoldingButtons.layer.insertSublayer(gradientView, at: 0)
然后我添加了这两行代码来删除导航栏底部边框:
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
结果如下:
任何人都可以帮助我使梯度均匀吗?
P.S。 : - 我确保将navigationBar.isTranslucent属性设置为false,两种情况下的颜色都设置为sRGB,我尝试在设置渐变之前和之后调用删除边框的行。
提前感谢。
答案 0 :(得分:0)
使导航栏完全透明,以便在那里显示视图的渐变图层。
self.navigationController!.navigationBar.backgroundColor = UIColor.clear
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isOpaque = false
self.navigationController?.navigationBar.isTranslucent = true
如果您希望以应用程序方式在AppDelegate中设置这些值
UINavigationBar.appearance().backgroundColor = UIColor.clear
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().isOpaque = false
UINavigationBar.appearance().isTranslucent = true