我想将UINavigationBar的颜色设置为黑色,使用alpha 0.6来查看我的界面。但如果我使用这段代码:
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.6)
self.navigationController?.navigationBar.translucent = true
它仍然看起来像alpha 1.0:
如何使用黑色透明色透明?
由于
答案 0 :(得分:1)
您必须使用相同的颜色设置navgationBar的背景图像,而不是设置barTintColor。请在此处查看类似的问题:
I can't set UINavigationBar's barTintColor to clearColor successfully
但是你必须得到这种特殊颜色的图像。你可以将这个图像放到你的项目中,然后使用
let image = UIImage(named: "yourimage'name")
获取图片。
或者您可以向视图控制器添加一个func:
func imageFromColor(color:UIColor,size:CGSize)->UIImage{
let rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
var image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContext(size)
image.drawInRect(rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image;
}
并在viewdidload中调用此函数:
let color=UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
let image=imageFromColor(color, size: CGSizeMake(1, 1))
self.navigationController?.navigationBar.translucent=true;
self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: UIBarMetrics.Default)
这样可行。
答案 1 :(得分:0)
斯威夫特3:
func imageFromColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(size)
image?.draw(in: rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
作为UIColor扩展程序
extension UIColor {
func toImage(withSize size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(self.cgColor)
context!.fill(rect)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(size)
image?.draw(in: rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
答案 2 :(得分:-1)
private static UIImage GetImageFromColor(UIColor color, CGSize size)
{
var rect = new CGRect(0, 0, size.Width, size.Height);
UIGraphics.BeginImageContextWithOptions(size, false, 0);
color.SetFill();
UIGraphics.RectFill(rect);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
var bgImage = GetImageFromColor(UIColor.FromRGBA(r,g,b,alpha),new CGSize(viewWidth,viewHeight));