MKPolylineRenderer CGContext drawPath blurry

137 views Asked by At

I'm trying to draw an arrow on a MKPolyline, which is working well by overriding the draw method, however the result is a blurred line. Any clues on why this might be?

It also does not show the arrows when zoomed out (zoomScale < 0.05), and also increases the line width as you zoom out,

Blurry example

Code below:

class ArrowPolylineRenderer: MKPolylineRenderer {
    override func applyStrokeProperties(to context: CGContext, atZoomScale zoomScale: MKZoomScale) {
        super.applyStrokeProperties(to: context, atZoomScale: zoomScale)
        UIGraphicsPushContext(context)
        if let ctx = UIGraphicsGetCurrentContext() {
            ctx.setLineWidth(self.lineWidth)
        }
    }

    override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
        if self.polyline.pointCount < 2 { return }
        let mapPoints = self.polyline.points()
        let startPoint = mapPoints[0]
        let endPoint = mapPoints[1]
        let p = CGMutablePath()
        if zoomScale >= 0.05 {
            let midPoint = self.point(for: MKMapPoint(x: (startPoint.x + endPoint.x)/2, y: (startPoint.y + endPoint.y)/2))
            let originX = endPoint.x - startPoint.x
            let originY = endPoint.y - startPoint.y
            let bearingR = atan2f(Float(originY), Float(originX))
            let p1 = CGPoint(x: midPoint.x - 60 / (zoomScale + 0.5), y: midPoint.y + 80 / (zoomScale + 0.5))
            let p2 = CGPoint(x: midPoint.x + 60 / (zoomScale + 0.5), y: midPoint.y)
            let p3 = CGPoint(x: midPoint.x - 60 / (zoomScale + 0.5), y: midPoint.y - 80 / (zoomScale + 0.5))
            let points = [p1, p2, p3]
            let t1 = CGAffineTransform(translationX: midPoint.x, y: midPoint.y)
            let t2 = t1.rotated(by: CGFloat(bearingR))
            let t3 = t2.translatedBy(x: -midPoint.x, y: -midPoint.y)
            p.addLines(between: points, transform: t3)
        }
        
        p.addLines(between: [self.point(for: startPoint), self.point(for: endPoint)])
        p.closeSubpath()
        context.setStrokeColor(UIColor.yellow.cgColor)
        context.setLineWidth(5/zoomScale)
        context.addPath(p)
        context.strokePath()
    }
}
0

There are 0 answers