iOS开发好文键盘上的鼓手iOS菜鸟级开发

iOS-导航栏背景色和透明度探究

2016-08-19  本文已影响14342人  鲲鹏DP

首先,我们来看看通过以下设置将会对导航栏产生什么影响

1.设置背景色--backgroundColor

 UINavigationBar * bar = self.navigationController.navigationBar;
bar.backgroundColor = [UIColor redColor];
Snip20160819_1.png

效果:不透明,不是我们想要的纯红色

Snip20160819_3.png
UINavigationBar被设置为纯红色.
分析:

整个导航栏看上去之所以呈现淡红色,是因为上面还有几层遮盖,且遮盖并非cleancolor,效果叠加,所以显示出来不为纯红色.还有一点值得注意,导航栏下面颜色深,而上面一部分颜色较浅,这是因为UINavigationBar高度为44,而其上面的View的高度为64.

2.设置背景图片--BackgroundImage


- (UIImage *) imageWithFrame:(CGRect)frame alphe:(CGFloat)alphe {
    frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
   UIColor *redColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:alphe];
    UIGraphicsBeginImageContext(frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [redColor CGColor]);
    CGContextFillRect(context, frame);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
 UINavigationBar * bar = self.navigationController.navigationBar;
    UIImage *bgImage = [self imageWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64) alphe:1.0];
    [bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
Snip20160819_4.png
半透明红色,上下颜色均匀
Snip20160819_5.png
UINavigationBarBackground被设置为红色,与设置backgroundColor相比少了两层View

3. 设置barTintColor

 UINavigationBar * bar = self.navigationController.navigationBar;
 bar.barTintColor = [UIColor redColor];
Snip20160819_8.png
均匀,不透明纯红色
Snip20160819_10.png
最上面一层View变为红色

4. translucent属性

Snip20160819_17.png

为什么会出现上面的效果呢?

 New behavior on iOS 7.
 Default is YES.
 You may force an opaque background by setting the property to NO.
 If the navigation bar has a custom background image, the default is inferred
 from the alpha values of the image—YES if it has any pixel with alpha < 1.0
 If you send setTranslucent:YES to a bar with an opaque custom background image
 it will apply a system opacity less than 1.0 to the image.
 If you send setTranslucent:NO to a bar with a translucent custom background image
 it will provide an opaque background for the image using the bar's barTintColor if defined, or black
 for UIBarStyleBlack or white for UIBarStyleDefault if barTintColor is nil.
 Default is NO on iOS 6 and earlier. Always YES if barStyle is set to UIBarStyleBlackTranslucent
Snip20160819_22.png
上一篇 下一篇

猜你喜欢

热点阅读