[英]How do you make a navigation bar colored and translucent (iOS)?
变色部分来自这里 。 我只是从这里添加了模糊部分。 我不知道这是否是模糊的最佳解决方案,但它正在起作用。 您将需要对导航栏进行子类化,但是没有任何痛苦。 如果模糊视图的alpha值稍微降低,发现效果更好,则您必须对此稍作练习。
extension UIColor {
func toImage() -> UIImage? {
return toImageWithSize(size: CGSize(width: 1, height: 1))
}
func toImageWithSize(size: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(size)
if let ctx = UIGraphicsGetCurrentContext() {
let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height)
ctx.setFillColor(self.cgColor)
ctx.addRect(rectangle)
ctx.drawPath(using: .fill)
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return colorImage
} else {
return nil
}
}
}
extension UIImage {
func imageWithAlpha(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
class CustomNavBar: UINavigationBar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setBackgroundImage(UIColor.blue.toImage()?.imageWithAlpha(alpha: 0.5), for: .default)
addBlurEffect()
}
func addBlurEffect() {
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
var frame = bounds
frame.origin.y -= 20
frame.size.height += 20
visualEffectView.frame = frame
visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
visualEffectView.alpha = 0.9
insertSubview(visualEffectView, at: 0)
sendSubview(toBack: visualEffectView)
}
}
只需设置导航栏的颜色,然后设置透明度。
navigationController?.navigationBar.barTintColor = UIColor.green
navigationController?.navigationBar.alpha = 0.5
那应该做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.