7

我正在尝试使用 MKMapSnapshotter 的 startWithCompletionHandler 方法获取地图视图的快照。并且我想将自定义引脚注释视图添加到快照中。我的自定义注释视图中有一个标签。所以当我获取快照时我无法显示该标签。这是代码:

 let snapshotter = MKMapSnapshotter(options: options)
    snapshotter.startWithCompletionHandler() {
        snapshot, error in

        if error != nil {
            completion(image: nil, error: error)
            return
        }

        let image = snapshot.image
        let pin = MKPinAnnotationView(annotation: nil, reuseIdentifier: "") // I want to use custom annotation view instead of  MKPinAnnotationView
        let pinImage = UIImage(named: "pinImage")

        UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale);
        image.drawAtPoint(CGPointMake(0, 0))
        var homePoint = snapshot.pointForCoordinate(coordinates[0])
        pinImage!.drawAtPoint(homePoint)

        pinImage!.drawAtPoint(snapshot.pointForCoordinate(coordinates[1]))

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        completion(image: finalImage, error: nil)
    }

如您所见,drawAtPoint 是 UIImage 的函数。我尝试使用 UIImageView 然后将标签作为子视图添加到 imageView 但我不能将 drawAtPoint 与 imageView 一起使用,所以我的问题是我无法将标签添加到 mapView 快照。

您可以在链接中看到我的意思: https ://www.dropbox.com/s/83hnkiqi87uy5ab/map.png?dl=0

谢谢你的建议。

4

1 回答 1

11

Create Custom AnnotationView Class.When you create MKMapSnapshotter define MKPointAnnotation with coordinate and title.After that define annotationView from your Custom Class.You can init custom annotationView with MKPointAnnotation. And use drawViewHierarchyInRect method instead of drawAtPoint.

Your code must be like that.

    let snapshotter = MKMapSnapshotter(options: options)
    snapshotter.startWithCompletionHandler() {
        snapshot, error in

        if error != nil {
            completion(image: nil, error: error)
            return
        }

        let image = snapshot.image
        var annotation = MKPointAnnotation()
        annotation.coordinate = coordinates[0]
        annotation.title = "Your Title"

        let annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: "annotation")
        let pinImage = annotationView.image

        UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale);

        image.drawAtPoint(CGPointMake(0, 0)) //map

//            pinImage!.drawAtPoint(snapshot.pointForCoordinate(coordinates[0]))                        

       annotationView.drawViewHierarchyInRect(CGRectMake(snapshot.pointForCoordinate(coordinates[0]).x, snapshot.pointForCoordinate(coordinates[0]).y, annotationView.frame.size.width, annotationView.frame.size.height), afterScreenUpdates: true)


        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        completion(image: finalImage, error: nil)
    }
于 2015-08-25T14:45:20.507 回答