1 功能描述
开发中经常遇到这样的需求:view2显示在view1上面,透过view2可以渐渐的看到view1.效果如图1所示:view1是一个imageView,view2是一个普通view。view1与view2完全重叠,view2从下到上由灰色到白色,由不透明到透明。图2为只有view2的效果,图3为只有view1的效果。
2 代码如下
如果只想颜色渐变,而不需要透明度的渐变,可以将alpha设为1.0。
1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.bounds]; 4 imgView.image = [UIImage imageNamed:@"sun"]; 5 [self.view addSubview:imgView]; 6 7 UIView *gradView = [[UIView alloc] initWithFrame:self.view.bounds]; 8 CAGradientLayer *layer = [self getGradientWithFrame:gradView.bounds]; 9 [gradView.layer insertSublayer:layer atIndex:0]; 10 [self.view addSubview:gradView]; 11 } 12 13 - (CAGradientLayer *)getGradientWithFrame:(CGRect) frame { 14 int colorOneV = 33; 15 int colorTwoV = 33; 16 int colorThreeV = 33; 17 // 设置颜色与不透明度alpha,如果只想渐变而不想透明,可以将alpha设为1.0。 18 UIColor *colorOne = [UIColor colorWithRed:(colorOneV/255.0) green:(colorOneV/255.0) blue:(colorOneV/255.0) alpha:0.0]; 19 UIColor *colorTwo = [UIColor colorWithRed:(colorTwoV/255.0) green:(colorTwoV/255.0) blue:(colorTwoV/255.0) alpha:0.5]; 20 UIColor *colorThree = [UIColor colorWithRed:(colorThreeV/255.0) green:(colorThreeV/255.0) blue:(colorThreeV/255.0) alpha:1.0]; 21 NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, colorThree.CGColor , nil]; 22 NSNumber *stopOne = [NSNumber numberWithFloat:0.0]; 23 NSNumber *stopTwo = [NSNumber numberWithFloat:0.5]; 24 NSNumber *stopThree = [NSNumber numberWithFloat:1.0]; 25 NSArray *locations = [NSArray arrayWithObjects:stopOne, stopTwo, stopThree, nil]; 26 // 渐变图层 27 CAGradientLayer *layer = [CAGradientLayer layer]; 28 layer.colors = colors; 29 layer.locations = locations; 30 layer.frame = frame; 31 return layer; 32 }
时间: 2024-10-20 01:40:06