将UI导航栏设置为部分半透明的Swift xCode

时间:2015-07-19 22:00:22

标签: ios xcode swift uinavigationbar

我想让我的导航栏有一种颜色但不完全半透明。 这是我的代码及其结果:

        UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().translucent = true
    UINavigationBar.appearance().barTintColor = UIColor(red: 0, green: 107/255, blue: 178/255, alpha: 0.5)

all translucent

但如果我将'半透明'变为假,即使用此代码:

        UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().barTintColor = UIColor(red: 0, green: 107/255, blue: 178/255, alpha: 0.5)

我得到了这个结果: second result

如何使条形图的alpha值为0.5或“半透明”?

谢谢,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我会为导航栏设置半透明的背景图像。

使用此代码:

UINavigationBar.appearance().setBackgroundImage(UIColor.green.toImage()?.imageWithAlpha(alpha: 0.5), for: .default)

使用了两个扩展程序:

从UIColor创建一个UIImage:

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
                }
            }   
        }

使用指定的Alpha:

从UIImage创建一个新的UIImage
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
    }
}