Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To paint a <code>MKPolyline</code> with a gradient, you can use a custom subclass of <code>MKPolylineView</code>. As CoreGraphics does not support stroking a path with a gradient, we have to </p> <ol> <li>convert the path to a shape that traces the paths edge using <code>CGPathCreateCopyByStrokingPath</code></li> <li>clip the context to that shape</li> <li>fill using <code>CGContextDrawLinearGradient</code></li> </ol> <p>Here is a subclass to get you started:</p> <pre><code>@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 </code></pre> <p>Here is a screenshot of a path drawn with the class above:</p> <p><img src="https://i.stack.imgur.com/XrxJl.png" alt="screenshot of a path with a gradient"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload