两段代码,首先是使用方法
01 |
CGContextRef context = UIGraphicsGetCurrentContext(); |
02 |
NSArray *colors = [NSArray arrayWithObjects: |
03 |
[UIColor colorWithRed:225.0 / 255.0 green:225.0 / 255.0 blue:225.0 / 255.0 alpha:1.0], |
04 |
[UIColor colorWithRed:168.0 / 255.0 green:168.0 / 255.0 blue:168.0 / 255.0 alpha:1.0], |
05 |
nil]; |
06 |
[self _drawGradientColor:context |
07 |
rect:CGRectMake(rX, rY, rW, rH) |
08 |
options:kCGGradientDrawsAfterEndLocation |
09 |
colors:colors]; |
10 |
CGContextStrokePath(context); // 描线,即绘制形状 |
11 |
CGContextFillPath(context); // 填充形状内的颜色 |
在一段就是绘制背景色渐变的矩形
01 |
/** |
02 |
* 绘制背景色渐变的矩形,p_colors渐变颜色设置,集合中存储UIColor对象(创建Color时一定用三原色来创建) |
03 |
**/ |
04 |
- ( void )_drawGradientColor:(CGContextRef)p_context |
05 |
rect:(CGRect)p_clipRect |
06 |
options:(CGGradientDrawingOptions)p_options |
07 |
colors:(NSArray *)p_colors { |
08 |
CGContextSaveGState(p_context); // 保持住现在的context |
09 |
CGContextClipToRect(p_context, p_clipRect); // 截取对应的context |
10 |
int colorCount = p_colors.count; |
11 |
int numOfComponents = 4; |
12 |
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB(); |
13 |
CGFloat colorComponents[colorCount * numOfComponents]; |
14 |
for ( int i = 0; i < colorCount; i++) { |
15 |
UIColor *color = p_colors[i]; |
16 |
CGColorRef temcolorRef = color.CGColor; |
17 |
const CGFloat *components = CGColorGetComponents(temcolorRef); |
18 |
for ( int j = 0; j < numOfComponents; ++j) { |
19 |
colorComponents[i * numOfComponents + j] = components[j]; |
20 |
} |
21 |
} |
22 |
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, colorCount); |
23 |
CGColorSpaceRelease(rgb); |
24 |
CGPoint startPoint = p_clipRect.origin; |
25 |
CGPoint endPoint = CGPointMake(CGRectGetMinX(p_clipRect), CGRectGetMaxY(p_clipRect)); |
26 |
CGContextDrawLinearGradient(p_context, gradient, startPoint, endPoint, p_options); |
27 |
CGGradientRelease(gradient); |
28 |
CGContextRestoreGState(p_context); // 恢复到之前的context |
29 |
} |
还有一种实现方式
1 |
CAGradientLayer *gradient = [CAGradientLayer layer]; |
2 |
gradient.frame = CGRectMake(rX, rY, rW, rH); |
3 |
gradient.colors = [NSArray arrayWithObjects: |
4 |
(id)[UIColor blackColor].CGColor, |
5 |
(id)[UIColor grayColor].CGColor, |
6 |
(id)[UIColor blackColor].CGColor, |
7 |
nil]; |
8 |
[self.view.layer insertSublayer:gradient atIndex:0]; |
时间: 2024-11-06 23:19:10