如何在Swift(iOS)中显示MKSnapshot

时间:2015-07-11 02:37:14

标签: ios swift mapkit

我正在尝试使用MKSnapshotter拍摄我的应用中固定位置的街景视图。我目前有这个代码:

var options: MKMapSnapshotOptions = MKMapSnapshotOptions();
    options.region = self.attractionDetailMap.region;
    options.size = self.attractionDetailMap.frame.size;
    options.scale = UIScreen.mainScreen().scale;

    var fileURL:NSURL = NSURL(fileURLWithPath: "path/to/snapshot.png")!;
    var snapshotter:MKMapSnapshotter = MKMapSnapshotter();
    snapshotter.startWithCompletionHandler { (snapshot:MKMapSnapshot!, error:NSError!) -> Void in
        if(error != nil) {
            println("error: " + error.localizedDescription);
            return;
        }
        let image:UIImage = snapshot.image;
        var data:NSData = UIImagePNGRepresentation(image);
        data.writeToURL(fileURL, atomically: true);

        var pin:MKAnnotationView = MKAnnotationView();
        UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale);
        image.drawAtPoint(CGPointMake(0.0, 0.0));
        var rect:CGRect = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
        for annotation in self.attractionDetailMap.annotations as! [MKAnnotation]{
            var point:CGPoint = snapshot.pointForCoordinate(annotation.coordinate);
            if(CGRectContainsPoint(rect, point)) {
                point.x = point.x + pin.centerOffset.x - (pin.bounds.size.width / 2.0);
                point.y = point.y + pin.centerOffset.y - (pin.bounds.size.height / 2.0);
                pin.image.drawAtPoint(point);
            }
        }

        var compositeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
        var data2:NSData = UIImagePNGRepresentation(compositeImage);
        data.writeToURL(fileURL, atomically: true);
        UIGraphicsEndImageContext();

现在我有了图像,我不知道如何将快照显示到我的mapview。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

因此MKMapSnapshotter类不用于在mapview中显示。它仅返回与mapview不兼容的地图图像。当我需要额外的性能时,我已经使用过它,比如在tableview单元格或collectionview中显示带有pin的地图。它比在tableview中显示实际的mapview要好得多。

因此,一旦获得快照,您只需将其加载到UIImageView中即可。它看起来就像mapview一样。