iOS: CGPathRef上绘制渐变颜色

来源:互联网 发布:淘宝男鞋排行榜 编辑:程序博客网 时间:2024/05/16 15:29

转自: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];}

 

效果:

Screen Shot 2015-01-28 at 11.21.45 PM


1 0
原创粉丝点击