【发布时间】:2017-11-11 20:10:53
【问题描述】:
如何使导航栏既是半透明的,又是有色调的,如下图所示:
我还希望它保留半透明导航栏的默认模糊效果(所以我不希望它看起来与图片一模一样,因为我也想要模糊效果。) 我觉得这应该很容易,但我花了一个小时寻找解决方案,但没有什么能按我想要的方式工作。 另外,我更喜欢 Interface Builder 解决方案,但如果没有 swift 也可以。
【问题讨论】:
标签: ios swift xcode interface-builder
如何使导航栏既是半透明的,又是有色调的,如下图所示:
我还希望它保留半透明导航栏的默认模糊效果(所以我不希望它看起来与图片一模一样,因为我也想要模糊效果。) 我觉得这应该很容易,但我花了一个小时寻找解决方案,但没有什么能按我想要的方式工作。 另外,我更喜欢 Interface Builder 解决方案,但如果没有 swift 也可以。
【问题讨论】:
标签: ios swift xcode interface-builder
变色部分来from here。我刚刚添加了模糊部分from here。我不知道它是否是模糊的最佳解决方案,但它正在工作。您将需要对导航栏进行子类化,但没有什么痛苦的。发现如果模糊视图稍微降低 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
应该可以的。
【讨论】: