加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 17:18:26 所属栏目:百科 来源:网络整理
导读:我想让我的导航栏有一种颜色但不完全半透明. 这是我的代码及其结果: UINavigationBar.appearance().setBackgroundImage(UIImage(),forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance
我想让我的导航栏有一种颜色但不完全半透明.
这是我的代码及其结果:

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)

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

UINavigationBar.appearance().setBackgroundImage(UIImage(),forBarMetrics: UIBarMetrics.Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().barTintColor = UIColor(red: 0,alpha: 0.5)

我得到这个结果:

如何使条形图的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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读