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;

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...