在Swift中使用MKMapSnapshotter绘制多边形和折线

时间:2019-06-06 12:36:16

标签: swift mkmapsnapshotter

我已使用MKMapSnapshotter下载某些坐标的图像并将其设置为ImageView。我正在使用MKMapSnapshotter,因为UITableViewCell中存在imageView。

我想对polygonpolyline做同样的事情,下面是我的点形状类型代码。

private func setMapImage(_ location: Coordinate) {
    let coordinate = "\(location.latitude),\(location.longitude)"
    if let image = SDImageCache.shared().imageFromCache(forKey: coordinate) {
        mapImageView.image = image
    } else {

        let rect = self.mapImageView.bounds
        let mapSnapshotOptions = MKMapSnapshotter.Options()

        // Set the region of the map that is rendered.
        let needleLocation = CLLocationCoordinate2DMake(location.latitude, location.longitude)
        let region = MKCoordinateRegion(center: needleLocation, latitudinalMeters: 200, longitudinalMeters: 200)
        mapSnapshotOptions.region = region

        // Set the scale of the image. We'll just use the scale of the current device, which is 2x scale on Retina screens.
        mapSnapshotOptions.scale = UIScreen.main.scale

        // Set the size of the image output.
        mapSnapshotOptions.size = CGSize(width: rect.width, height: rect.height)

        // Show buildings and Points of Interest on the snapshot
        mapSnapshotOptions.showsBuildings = true
        mapSnapshotOptions.showsPointsOfInterest = true

        let snapshot = MKMapSnapshotter(options: mapSnapshotOptions)
        snapshot.start { snapshot, error in
            guard let snapshot = snapshot, error == nil else {
                print("Failed to get snapshot \(error!.localizedDescription)")
                return
            }

            UIGraphicsBeginImageContextWithOptions(mapSnapshotOptions.size, true, 0)
            snapshot.image.draw(at: .zero)

            let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
            let pinImage = pinView.image

            var point = snapshot.point(for: needleLocation)

            if rect.contains(point) {
                let pinCenterOffset = pinView.centerOffset
                point.x -= pinView.bounds.size.width / 2
                point.y -= pinView.bounds.size.height / 2
                point.x += pinCenterOffset.x
                point.y += pinCenterOffset.y
                pinImage?.draw(at: point)
            }

            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            DispatchQueue.main.async { [weak self] in
                self?.mapImageView.image = image
                SDImageCache.shared().store(image, forKey: coordinate, completion: nil)
            }
        }
    }
}

要实现上述目的,我需要添加注释,然后从中绘制线条。我没有在MKMapSnapshotter上看到任何用于执行此操作的方法。

0 个答案:

没有答案