ios – MKMapSnapshotOptions:添加Custom Pin Annotation View或UIView的快照

前端之家收集整理的这篇文章主要介绍了ios – MKMapSnapshotOptions:添加Custom Pin Annotation View或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的功能.我尝试使用UIImageView然后我将标签添加到imageView作为subView但我不能使用drawView与imageView,所以我的问题是我无法添加标签到mapView快照.

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

谢谢你的建议.

解决方法

创建自定义AnnotationView类.当您创建MKMapSnapshotter时,使用坐标和标题定义MKPointAnnotation.之后,从Custom Class定义annotationView.您可以使用MKPointAnnotation初始化自定义annotationView.并使用drawViewHierarchyInRect方法而不是drawAtPoint.

你的代码必须是这样的.

let snapshotter = MKMapSnapshotter(options: options)
    snapshotter.startWithCompletionHandler() {
        snapshot,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,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)
    }
原文链接:https://www.f2er.com/iOS/328615.html

猜你在找的iOS相关文章