Core Graphices 设置渐变
Quartz 提供了两种设置渐变的方式 CGShadingRef
and CGGradientRef
尝试CGGradientRef 的使用
import <UIKit/UIKit.h> @interface GradientDemoA : UIView @property (nonatomic,copy,nonnull)NSArray *colorArray;
@property (nonatomic,copy,nonnull) NSArray *locations;
@property (nonatomic,assign)CGPoint startPoint;
@property (nonatomic,assign)CGPoint endPoint; - (void)showViewWithColorArray:(NSArray * _Nullable)colorArray GradientLocations:(NSArray * _Nullable)loc startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;
@end
#import "GradientDemoA.h" @implementation GradientDemoA - (instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor whiteColor];
}
return self;
} - (void)showViewWithColorArray:(NSArray *)colorArray GradientLocations:( NSArray *)loc startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint{ self.colorArray = colorArray;
self.locations = loc;
self.startPoint = startPoint;
self.endPoint = endPoint;
[self setNeedsDisplay];
} - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient;
size_t num_location = self.colorArray.count; CGFloat components[self.colorArray.count*]; for (int i=; i<self.colorArray.count; i++) {
CGFloat *colorComponents = (CGFloat *)CGColorGetComponents(((UIColor *)self.colorArray[i]).CGColor);
components[+i*] = colorComponents[];
components[+i*] = colorComponents[];
components[+i*] = colorComponents[];
components[+i*] = colorComponents[]; } CGFloat gendientLocations[self.locations.count]; for (int j= ; j<self.locations.count; j++) { gendientLocations[j] = (CGFloat)([self.locations[j] doubleValue]);
} // 参数的意义
/* 颜色空间
components cgfloat 数组 RGB的颜色值
{
red1,green1,blue1,alpha1,
red2,green2,blue2,alpha2,
...
}
gendientLocations 颜色渐变的点 CGFloat gendientLocation[2] = {0.0,.......,1.0}; num_location 颜色渐变点的个数;
*/ gradient = CGGradientCreateWithColorComponents(colorSpace, components, gendientLocations, num_location); /*
开始点与结束点的tan值决定了渐变的角度;
**/ // CGContextDrawLinearGradient(context, gradient, self.startPoint, self.endPoint, kCGGradientDrawsBeforeStartLocation); CGContextDrawRadialGradient(context, gradient, CGPointMake(, ), , CGPointMake(, ), , kCGGradientDrawsAfterEndLocation); CGGradientRelease(gradient); } @end
参数更具体的意义请查看:
http://blog.csdn.net/u012890117/article/details/17606755
测试代码:
- (void)gradientColor{
GradientDemoA *my = [[GradientDemoA alloc] initWithFrame:CGRectMake(, , , )]; [my showViewWithColorArray:@[[[UIColor redColor] colorWithAlphaComponent:1.0],[[UIColor redColor] colorWithAlphaComponent:0.0],[[UIColor redColor] colorWithAlphaComponent:0.8]] GradientLocations: @[@(0.1),@0.5,@(0.8)] startPoint:CGPointMake(,) endPoint:CGPointMake(, )]; [self.view addSubview:my];
}
图1:
图2: