绘制背景色渐变的矩形

两段代码,首先是使用方法

01CGContextRef 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}

还有一种实现方式

1CAGradientLayer *gradient = [CAGradientLayer layer];
2gradient.frame = CGRectMake(rX, rY, rW, rH);
3gradient.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];


转载于:https://my.oschina.net/hejunbinlan/blog/469797

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值