本文介绍了将UI导航栏设置为在Swift xCode中半透明的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make my navigation bar have a tinge of a colour but not go completely translucent.Here is the code I have and their results:

        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)

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

But if I turn the 'translucent' to false i.e use this code:

        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)

我得到了他的结果:

I get this result:

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

How do I make the bar have an alpha value of 0.5 or be 'part translucent'?

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

Thank you, any help will be appreciated.

推荐答案

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

I would set a translucent background image for the navigation bar.

使用此代码:

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

使用了两个扩展名:

从UIColor创建UIImage:

Create an UIImage from UIColor:

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:

Create a new UIImage from an UIImage with a specified Alpha:

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

这篇关于将UI导航栏设置为在Swift xCode中半透明的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 06:04