swiftmapkitmkoverlay

custom overlay(renderer) is getting cut of by map tiles (in some cases)


I wrote a custom renderer to represent a min and a max Radius. In some cases the renderer is not working as expected. It looks like the overlay is getting cut of by the map tiles.

min/max overlay on the map
See the full video

Here is how I did it. Did I miss something?

class RadiusOverlayRenderer: MKOverlayRenderer {

    override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {

        guard let overlay = self.overlay as? RadiusOverlay else {
            return
        }

        let maxRadiusRect = self.rect(for: overlay.boundingMapRect)
            .offsetBy(
                dx: CGFloat(-overlay.boundingMapRect.height)/2,
                dy: CGFloat(-overlay.boundingMapRect.width)/2
            )

        let minRadiusRect = CGRect(
            x: Double(maxRadiusRect.midX)-overlay.minRadRect.width/2,
            y: Double(maxRadiusRect.midY)-overlay.minRadRect.height/2,
            width: overlay.minRadRect.width,
            height: overlay.minRadRect.height)

        let aPath = CGMutablePath()
        aPath.addEllipse(in: maxRadiusRect)
        aPath.addEllipse(in: minRadiusRect)
        aPath.closeSubpath()

        context.setFillColor(overlay.color.cgColor)
        context.setAlpha(overlay.alpha)
        context.addPath(aPath)
        context.drawPath(using: .eoFillStroke)

    }

}

Solution

  • Notice that only the upper left parts are clipped?

    with .offsetBy you are drawing outside of the .boundingMapRect.

    Remove the .offsetBy...

    If you want to draw your circle at a different place, then adjust coordinate and / or boundingMapRect of your MKOverlay.