如何用渐变填充UIBezierPath?

我用UIBezierPath绘制了一个图。 我可以使用纯色填充graphics下的区域,但是我想用渐变填充graphics下面的区域,而不是使用纯色。 但我不知道如何使梯度适用于graphics,而不是整个视图,我已经阅读了几个问题,但没有发现任何适用的。

在这里输入图像说明

这是主要的graphics绘制代码:

// Draw the graph UIBezierPath *barGraph = [UIBezierPath bezierPath]; barGraph.lineWidth = 1.0f; [blueColor setStroke]; TCDataPoint *dataPoint = self.testData[0]; CGFloat x = [self convertTimeToXPoint:dataPoint.time]; CGFloat y = [self convertDataToYPoint:dataPoint.dataUsage]; CGPoint plotPoint = CGPointMake(x,y); [barGraph moveToPoint:plotPoint]; for (int ii = 1; ii < [self.testData count]; ++ii) { dataPoint = self.testData[ii]; x = [self convertTimeToXPoint:dataPoint.time]; y = [self convertDataToYPoint:dataPoint.dataUsage]; plotPoint = CGPointMake(x, y); [barGraph addLineToPoint:plotPoint]; } [barGraph stroke]; 

我一直试图通过试验下面的代码来填充图表,但说实话,我不知道我在做什么,尽pipe经历了各种教程和文档:

 [barGraph closePath]; CGFloat colors [] = { 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2); CGColorSpaceRelease(baseSpace); CGPoint startPoint = CGPointMake(CGRectGetMidX(self.bounds), self.topY); CGPoint endPoint = CGPointMake(CGRectGetMidX(self.bounds), self.bottomY); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextClip(context); CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); CGGradientRelease(gradient); 

最简单的方法是使用原始graphics贝塞尔path来帮助您构build蒙版,并将该蒙版施加到渐变图层上。 现在将图层添加到渐变图层的顶部。

因此,例如,制作一个CAShapeLayer,closuresgraphicsbezierpath,将其path设置为形状图层的path,并将其填充为黑色。 现在你有一个面具,就是graphics下方区域的形状。 现在制作CAGradientLayer,并将CAShapeLayer作为其mask 。 在前面,放置实际的graphics。

举例来说( EDITED ):

在这里输入图像说明

下面是我用来创build该绘图的代码(我的贝塞尔path非常简单,只有四点连接三行,但是您可以清楚地看到它下面的区域是渐变):

 CAShapeLayer* shape = [[CAShapeLayer alloc] init]; shape.frame = self.graph.bounds; CGFloat h = shape.frame.size.height; CGFloat w = shape.frame.size.width; NSArray* points = @[ [NSValue valueWithCGPoint:CGPointMake(0,h-50)], [NSValue valueWithCGPoint:CGPointMake(70,h-100)], [NSValue valueWithCGPoint:CGPointMake(140,h-75)], [NSValue valueWithCGPoint:CGPointMake(w,h-150)], ]; UIBezierPath* p = [UIBezierPath new]; [p moveToPoint:[points[0] CGPointValue]]; for (NSInteger i = 1; i < points.count; i++) [p addLineToPoint:[points[i] CGPointValue]]; shape.path = p.CGPath; shape.strokeColor = [UIColor blackColor].CGColor; shape.lineWidth = 2; shape.fillColor = nil; CAGradientLayer* grad = [[CAGradientLayer alloc] init]; grad.frame = self.graph.bounds; grad.colors = @[(id)[UIColor blueColor].CGColor, (id)[UIColor yellowColor].CGColor]; CAShapeLayer* mask = [[CAShapeLayer alloc] init]; mask.frame = self.graph.bounds; [p addLineToPoint:CGPointMake(w,h)]; [p addLineToPoint:CGPointMake(0,h)]; [p closePath]; mask.path = p.CGPath; mask.fillColor = [UIColor blackColor].CGColor; grad.mask = mask; [self.graph.layer addSublayer:grad]; [self.graph.layer addSublayer:shape];