在一个应用程序中,我绘制一个弯曲的UIBezierPath一个MKOverlayPathView类来显示飞行路线.这是我使用的代码:
06000
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context{
self.mapRect = mapRect;
CGContextSetRGBFillColor(context,1.0,1.0);
CGContextSetRGBstrokeColor(context,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);
}
这是正常工作,但我想要沿着该路径绘制一个渐变,而不是只填充颜色.这是开始变得非常棘手的地方.
我已经尝试了CGContextDrawLinearGradient(),但它还没有让我有用的.
解决方法
诀窍是使用行的笔画路径(CGContextReplacePathWithstrokedpath)并剪辑它(CGContextClip)来限制渐变到路径:
// Create a gradient from white to red
CGFloat colors [] = {
1.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;