沿着弯曲的UIBezierPath绘制渐变 [英] Draw gradient along a curved UIBezierPath
问题描述
在一个应用程序中,我绘制了一个弯曲的UIBezierPath和一个MKOverlayPathView类以显示飞行路线.这是我正在使用的代码:
In an app, I draw a curved UIBezierPath an an MKOverlayPathView class to show flight routes. This is the code I am using:
- (UIBezierPath *)pathForOverlayForMapRect:(MKMapRect)mapRect {
... bla bla bla ...
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:s];
[path addQuadCurveToPoint:e controlPoint:cp1];
[path addLineToPoint:e2];
[path addQuadCurveToPoint:s2 controlPoint:cp2];
[path closePath];
return path;
}
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context{
self.mapRect = mapRect;
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
CGContextSetLineWidth(context, mapRect.size.height/700);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextAddPath(context, [self pathForOverlayForMapRect:mapRect].CGPath);
[self updateTouchablePathForMapRect:mapRect];
CGContextDrawPath(context, kCGPathFillStroke);
}
这工作得很好,但我想沿该路径绘制渐变色,而不只是填充颜色.这就是它开始变得非常棘手的地方.
This is working just fine but I would like to draw a gradient along that path instead of just a fill color. And this is where it is starting to get very tricky.
我已经尝试过CGContextDrawLinearGradient(),但是还没有使我有用的地方.
I have experimented with CGContextDrawLinearGradient() but it hasn't got me anywhere useful yet.
推荐答案
诀窍是使用直线(CGContextReplacePathWithStrokedPath
)的描边路径并对其进行裁剪(CGContextClip
)以将渐变限制为该路径:
The trick is to use the stroke path of the line (CGContextReplacePathWithStrokedPath
) and clip it (CGContextClip
) to restrict the gradient to the path:
// Create a gradient from white to red
CGFloat colors [] = {
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 0.0, 1.0
};
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
CGColorSpaceRelease(baseSpace), baseSpace = NULL;
CGContextSetLineWidth(context, mapRect.size.height/700);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextAddPath(context, [self pathForOverlayForMapRect:mapRect].CGPath);
CGContextReplacePathWithStrokedPath(context);
CGContextClip(context);
[self updateTouchablePathForMapRect:mapRect];
// Define the start and end points for the gradient
// This determines the direction in which the gradient is drawn
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient), gradient = NULL;
这篇关于沿着弯曲的UIBezierPath绘制渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!