Draw CAGradient within MKPolyLineView

老子叫甜甜 提交于 2019-11-30 07:37:28

To paint a MKPolyline with a gradient, you can use a custom subclass of MKPolylineView. As CoreGraphics does not support stroking a path with a gradient, we have to

  1. convert the path to a shape that traces the paths edge using CGPathCreateCopyByStrokingPath
  2. clip the context to that shape
  3. fill using CGContextDrawLinearGradient

Here is a subclass to get you started:

@interface TWOGradientPolylineView : MKPolylineView

@end

@implementation TWOGradientPolylineView

- (void)strokePath:(CGPathRef)path inContext:(CGContextRef)context
{
    CGFloat lineWidth = CGContextConvertSizeToUserSpace(context, (CGSize){self.lineWidth, self.lineWidth}).width;
    CGPathRef pathToFill = CGPathCreateCopyByStrokingPath(path, NULL, lineWidth, self.lineCap, self.lineJoin, self.miterLimit);
    CGRect rect = CGPathGetBoundingBox(pathToFill);
    CGContextAddPath(context, pathToFill);
    CGPathRelease(pathToFill);
    CGContextClip(context);

    CGFloat gradientLocations[2] = {0.0f, 1.0f};
    CGFloat gradientColors[8] = {1.0f, 0.0f, 0.0f, 0.75f, 1.0f, 1.0f, 0.0f, 0.75f};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradientColors, gradientLocations, 2);
    CGColorSpaceRelease(colorSpace);

    CGPoint gradientStart = rect.origin;
    CGPoint gradientEnd = {CGRectGetMaxX(rect), CGRectGetMaxY(rect)};

    CGContextDrawLinearGradient(context, gradient, gradientStart, gradientEnd, kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);
}

@end

Here is a screenshot of a path drawn with the class above:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!