如何为MKPolygonRenderer提供图像?

时间:2018-07-08 03:54:22

标签: ios swift mapkit mkmapview mkpolygon

我的代码正确获取图像并提供mapView的边界。我想将图像放置在范围之内,但不确定如何。我可以用一种颜色填充它,但需要帮助使它成为图像。

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolygonRenderer(overlay: overlay)
    //renderer.fillColor = UIColor.red -> works
    return renderer
}

如何用我下载的这张图片填充它?https://radar.weather.gov/ridge/Conus/RadarImg/latest_radaronly.gif

1 个答案:

答案 0 :(得分:0)

使用MKOverlayRenderer的子类,您将能够在实际的UIImage上呈现MKPolygon覆盖

class CustomOverlayRenderer: MKOverlayRenderer  {

    private let overlayImage: UIImage?

    init(overlay: MKOverlay, image: UIImage? = nil) {
        self.overlayImage = image
        super.init(overlay: overlay)
    }

    override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
        guard let cgImage = self.overlayImage?.cgImage else { return }

        let rect = self.rect(for: overlay.boundingMapRect)

        context.scaleBy(x: 1.0, y: -1.0)
        context.translateBy(x: 0, y: -rect.height)
        context.draw(cgImage, in: rect)
    }

}

只需将您的委托方法更改为使用CustomOverlayRenderer,就像这样:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    return CustomOverlayRenderer(overlay: overlay, image: UIImage(named: "latest_radaronly.gif")!)
}