最近想整一下导航栏渐变,然后发现UIColor的一个方法: colorWithAlphaComponent: 通过此方法给视图一个alpha值,改变该视图的透明度,但其上的自视图控件透明度不受影响。
// Returns a color in the same color space as the receiver with the specified alpha component.
- (UIColor *)colorWithAlphaComponent:(CGFloat)alpha;
创建两个视图UIView:
#pragma mark -懒加载
- (UIView *)fView
{
if (!_fView) {
_fView = [[UIView alloc] initWithFrame:CGRectMake(10, 100, SCREEN_Width - 20, 200)];
_fView.backgroundColor = [UIColor blueColor];
}
return _fView;
}
- (UIView *)subView
{
if (!_subView) {
_subView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, SCREEN_Width - 60, 160)];
_subView.backgroundColor = [UIColor redColor];
}
return _subView;
}
添加到控制器视图上,_subView添加到_fView上:
[self.view addSubview:self.fView];
[self.fView addSubview:self.subView];
默认效果:
default.png- 直接设置视图的alpha值,其上的子控件透明度也会改变:
self.fView.alpha = 0.3;
1.png
2. 通过UIColor的类方法+ (UIColor *)colorWithWhite:(CGFloat)white alpha:(CGFloat)alpha;
self.fView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
2.png
3. 通过UIColor的实例方法- (UIColor *)colorWithAlphaComponent:(CGFloat)alpha;
self.fView.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.1];
3.png
4.通过UIColor方法:+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;
self.fView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.3];
4.png
5. 16进制方式设置颜色时 设置alpha,实质还是通过RGBA设置颜色:
self.fView.backgroundColor = [Tools colorWithHex:0x0000FF alpha:0.3];
5.png
这样看,除了直接设置视图的alpha会影响到子视图的透明度,其他方式均不影响到其子视图的透明度。
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Tools : NSObject
+ (UIColor *)colorWithHex:(unsigned int)hex;
+ (UIColor *)colorWithHex:(unsigned int)hex alpha:(CGFloat)alpha;
@end
#import "Tools.h"
@implementation Tools
+ (UIColor *)colorWithHex:(unsigned int)hex alpha:(CGFloat)alpha{
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0
green:((float)((hex & 0xFF00) >> 8)) / 255.0
blue:((float)(hex & 0xFF)) / 255.0
alpha:alpha];
}
+ (UIColor *)colorWithHex:(unsigned int)hex
{
return [self colorWithHex:hex alpha:1];
}
@end
网友评论