Ios 在Swift xCode中将UI导航栏设置为部分半透明

Ios 在Swift xCode中将UI导航栏设置为部分半透明,ios,xcode,swift,uinavigationbar,Ios,Xcode,Swift,Uinavigationbar,我想让我的导航栏有一点颜色,但不是完全半透明。 以下是我的代码及其结果: UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().translucent = true

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

        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)

但如果我将“半透明”设置为false,即使用以下代码:

        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)
UINavigationBar.appearance().setBackgroundImage(UIColor.green.toImage()?.imageWithAlpha(alpha: 0.5), for: .default)
我得到这个结果:

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


谢谢,如果您有任何帮助,我们将不胜感激。

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

使用此代码:

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

请尝试UINavigationBar.appearance().tintColor属性