在我的应用程序委托&didFinishLaunchingWithOptions函数中,我尝试自定义导航栏的外观。
[UINavigationBar appearance].translucent = NO;
[[UINavigationBar appearance]
setBackgroundImage:[UIImage
imageWithColor:[UIColor whiteColor]
size:CGSizeMake(1.0f, 1.0f)
]
forBarMetrics:UIBarMetricsDefault
];
[UINavigationBar appearance].shadowImage = [UIImage
imageWithColor:[UIColor redColor]
size:CGSizeMake(0.5f, 0.5f)
];
我期待一个1px高的不透明红色阴影。相反,我给了一个2px高的半透明红色阴影。怎么能让它看起来像我想要的那样?我已经为UITabBar完成了类似的外观设置。另一方面,它表现得很好。
创建动态图像的类别功能定义如下:
+ (UIImage*)imageWithColor:(UIColor *)color size:(CGSize)size
{
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
答案 0 :(得分:17)
您需要创建一个支持视网膜的图形上下文:
let pixelScale = UIGraphicsBeginImageContextWithOptions(fillRect.size, false, UIScreen.main.scale)
之后,您的阴影图像将变为1个物理像素高。
以下是完整的代码:
extension UIImage {
static func imageWithColor(color: UIColor) -> UIImage {
let pixelScale = UIScreen.main.scale
let pixelSize = 1 / pixelScale
let fillSize = CGSize(width: pixelSize, height: pixelSize)
let fillRect = CGRect(origin: CGPoint.zero, size: fillSize)
UIGraphicsBeginImageContextWithOptions(fillRect.size, false, pixelScale)
let graphicsContext = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(graphicsContext, color.CGColor)
CGContextFillRect(graphicsContext, fillRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
在GitHub上:
答案 1 :(得分:-2)
呃......这就是你想要的吗?
在我的视图控制器中,我只添加了一个高度为1像素,偏移量为44像素的UIView:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
[self setupNavBar];
}
-(void)setupNavBar
{
self.navigationItem.title = @"Contacts";
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
UIView *bar = [[UIView alloc] initWithFrame:CGRectMake(0, 44, applicationFrame.size.width, 1.0)];
bar.backgroundColor = [UIColor redColor];
[self.navigationController.navigationBar addSubview:bar];
}
您可以将颜色更改为您想要的颜色。