我有以下函数,它接受三个参数,通过使用mkmapsnapshot生成快照图像。该函数正确地生成快照,但我想以字节数组的形式返回生成的快照。我认为它可以通过使用回调,完成处理程序或类似的东西来执行,如果有任何答案,我很感激。
func generateImageSnapshot(location:CLLocationCoordinate2D, width: CGFloat, height: CGFloat) {
let options = MKMapSnapshotter.Options()
options.camera = MKMapCamera(lookingAtCenter: location, fromDistance: 300, pitch: 0, heading: 0)
options.mapType = .standard
options.size = CGSize(width: width, height: height)
let snapshotter = MKMapSnapshotter(options: options)
snapshotter.start() { snapshot, _ in
let mapImage = snapshot?.image
let finalImage = UIGraphicsImageRenderer(size: options.size).image { _ in
mapImage?.draw(at: .zero)
let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = pinView.image
let point = snapshot?.point(for: location)
pinImage?.draw(at: point!)
}
return finalImage.pngData() // This line is needed to be returned by the function
}
}`
我已经用下面的代码片段解决了这个问题:
func generateImageSnapshot(location: CLLocationCoordinate2D, width: CGFloat, height: CGFloat, completion: @escaping (Data?) -> Void) {
let options = MKMapSnapshotter.Options()
options.camera = MKMapCamera(lookingAtCenter: location, fromDistance: 300, pitch: 0, heading: 0)
options.mapType = .standard
options.size = CGSize(width: width, height: height)
let snapshotter = MKMapSnapshotter(options: options)
snapshotter.start { snapshot, error in
guard let snapshot = snapshot, error == nil else {
completion(nil)
return
}
let mapImage = snapshot.image
let finalImage = UIGraphicsImageRenderer(size: options.size).image { _ in
mapImage.draw(at: .zero)
_ = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = UIImage(systemName: "mappin")
let point = snapshot.point(for: location)
pinImage?.draw(at: point)
}
let imageData = finalImage.pngData()
completion(imageData)
}
}