ios – 沿弯曲的UIBezierPath绘制梯度

一个应用程序中,我绘制一个弯曲的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;

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...