CAGradientLayer 处理渐变

CAGradientLayer可以方便的处理颜色渐变。

 1 self.view.backgroundColor = [UIColor whiteColor];
 2     UIImage *image = [UIImage imageNamed:@"mountains.png"]; // 原图
 3     
 4     CALayer *imageLayer = [CALayer layer];
 5     imageLayer.borderColor = [UIColor greenColor].CGColor;
 6     imageLayer.borderWidth = 2;
 7     imageLayer.contents = (id)image.CGImage;
 8     imageLayer.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
 9     imageLayer.position = CGPointMake(160, 130);
10     [self.view.layer addSublayer:imageLayer];   // 将原图转换为CALayer
11 
12     CALayer *reflectionLayer = [CALayer layer];     // 设置倒影层
13     reflectionLayer.contents = imageLayer.contents;
14     reflectionLayer.bounds = imageLayer.bounds;
15     reflectionLayer.position = CGPointMake(160, 330);
16     reflectionLayer.borderColor = imageLayer.borderColor;
17     reflectionLayer.borderWidth = imageLayer.borderWidth;
18     reflectionLayer.opacity = 0.5;
19     
20     [reflectionLayer setValue:[NSNumber numberWithFloat:DEGREES_TO_RADIANS(180)] forKeyPath:@"transform.rotation.x"];  // 仅仅将图片层沿X轴反转180度
21 
22     CAGradientLayer *gradientLayer = [CAGradientLayer layer];  // 设置渐变效果
23     gradientLayer.bounds = reflectionLayer.bounds;
24     gradientLayer.borderWidth = 2;
25     gradientLayer.borderColor = [UIColor redColor].CGColor;
26     gradientLayer.position = CGPointMake(reflectionLayer.bounds.size.width / 2,
27                                          reflectionLayer.bounds.size.height * 0.65);
28     gradientLayer.colors = [NSArray arrayWithObjects:
29                             (id)[[UIColor greenColor] CGColor],
30                             (id)[[UIColor clearColor] CGColor],
31                             (id)[[UIColor whiteColor] CGColor], nil];
32     gradientLayer.startPoint = CGPointMake(0.5, 0.5);
33     gradientLayer.endPoint = CGPointMake(0.5, 1.0);
34 
35     reflectionLayer.mask = gradientLayer;
36     [self.view.layer addSublayer:reflectionLayer];

 

posted @ 2013-02-08 22:12  diablo大王  阅读(1737)  评论(0编辑  收藏  举报