MKMapSnapshotOptions:添加自定义引脚注解视图或UIView的快照

我正在尝试使用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的function。 我尝试使用UIImageView然后我将标签添加到imageView作为子视图,但我不能使用drawAtPoint与imageView所以我的问题是我不能添加标签到mapView快照。

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

谢谢你的build议。

创build自定义AnnotationView类。当你创buildMKMapSnapshotter时,用坐标和标题定义MKPointAnnotation。然后在你的Custom Class中定义annotationView。你可以使用MKPointAnnotation来初始化自定义annotationView。 并使用drawViewHierarchyInRect方法而不是drawAtPoint。

你的代码必须是这样的。

  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) }