CAGradientLayer可以方便的处理颜色渐变,它有以下几个主要的属性:
1、@property(copy) NSArray *colors 渐变颜色的数组
[NSArray arrayWithObjects:(id)[[[UIColor blackColor] colorWithAlphaComponent:1]CGColor],
(id)[[[UIColor yellowColor] colorWithAlphaComponent:1]CGColor],
(id)[[[UIColor blueColor] colorWithAlphaComponent:1] CGColor],
(id)[[UIColor clearColor] CGColor],
nil];
2、@property(copy) NSArray *locations 渐变颜色的区间分布,locations的数组长度和color一致,默认是nil,会平均分布。
[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:0.1],
[NSNumber numberWithFloat:09],
[NSNumber numberWithFloat:1.0],
nil];
3、@property CGPoint startPoint 映射locations中第一个位置,用单位向量表示,比如(0,0)表示从左上角开始变化。默认值是(0.5,0.0)。 4、@property CGPoint endPoint 映射locations中最后一个位置,用单位向量表示,比如(1,1)表示到右下角变化结束。默认值是(0.5,1.0)。
使用方法:
1.添加QuartzCore.framework
2.#import <QuartzCore/QuartzCore.h>
3.方法
- (CAGradientLayer *)shadowAsInverse { CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init]; CGRect newGradientLayerFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); gradientLayer.frame = newGradientLayerFrame; //添加渐变的颜色组合 gradientLayer.colors = [NSArray arrayWithObjects:(id)[[[UIColor blackColor] colorWithAlphaComponent:1]CGColor], (id)[[[UIColor yellowColor] colorWithAlphaComponent:1]CGColor], (id)[[[UIColor redColor] colorWithAlphaComponent:1] CGColor], (id)[[UIColor clearColor] CGColor], nil]; gradientLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.2], [NSNumber numberWithFloat:0.4], [NSNumber numberWithFloat:0.9], nil]; gradientLayer.startPoint = CGPointMake(0,0); gradientLayer.endPoint = CGPointMake(1,1); return gradientLayer; }
4.调用:
UILabel *lab = [[UILabelalloc] initWithFrame:CGRectMake(40,20, 50,30)];
[lab.layeraddSublayer:[self shadowAsInverse]];
[self.viewaddSubview:lab];
效果就这样子了。。。