您的位置:首页 > 移动开发 > IOS开发

iOS: CGPathRef上绘制渐变颜色

2017-04-01 16:56 399 查看
转自:https://www.mgenware.com/blog/?p=2396

在iOS Core Graphics中绘制渐变颜色主要是通过使用
CGContextDraw(xxx)Gradient
相关函数,比如,常见的线性渐变就是
CGContextDrawLinearGradient
函数,这里帖子封装了绘制渐变颜色的具体代码过程,我们拿过来直接用,只不过原帖代码是用
CGContextAddRect
画了一个矩形,我们改一下去画
CGPathRef
。这里无论是什么形状其实无所谓,原理都是用来做Clip,所以需要在
CGContextClip
函数前调用
CGContextAddPath
函数把
CGPathRef
加入到Context中。

另外一个需要注意的地方是渐变的方向,方向是由两个点控制的,点的单位就是坐标。因此需要正确从
CGPathRef
中找到正确的点,方法当然有很多种看具体实现,本例中,我就是简单得通过调用
CGPathGetBoundingBox
函数,返回
CGPathRef
的矩形区域,然后根据这个矩形取两个点,读者可以根据自行需求修改具体代码。

OK,把代码封装成一个方法,类似这样:

/**
* 修改自http://www.raywenderlich.com/32283/core-graphics-tutorial-lines-rectangles-and-gradients
*/
- (void)drawLinearGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };

NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];

CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);

CGRect pathRect = CGPathGetBoundingBox(path);

//具体方向可根据需求修改
CGPoint startPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMinY(pathRect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMaxY(pathRect));

CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);

CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}


 

接下来就可以使用了,示例代码:

- (void)viewDidLoad {
[super viewDidLoad];

//创建CGContextRef
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();

//创建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();

//绘制Path
CGRect rect = CGRectInset(self.view.bounds, 30, 30);
CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetHeight(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetHeight(rect) * 2 / 3);
CGPathCloseSubpath(path);

//绘制渐变
[self drawLinearGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];

//注意释放CGMutablePathRef
CGPathRelease(path);

//从Context中获取图像,并显示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
}


 

效果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: