我自己学习Swift 3,而我目前的学习项目包括允许用户拍摄照片并获取当前位置固定的地图快照。
我从2015年8月开始依赖this answer,从2016年6月起依赖this answer作为指导,但我仍然无法找到正确的道路。
现在,我可以......
但是我无法放置引脚。我知道我的代码不完整且无效 - 所以这不仅仅是一个调试问题。以下是我一直在使用的内容(以及基于上述链接的许多变体):
let snapShotter = MKMapSnapshotter(options: mapSnapshotOptions)
snapShotter.start() {
snapshot, error in
guard let snapshot = snapshot else {
return
}
let image = snapshot.image
let annotation = MKPointAnnotation()
annotation.coordinate = needleLocation // is a CLLocationCoordinate2D
annotation.title = "My Title"
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotation")
// I want to push the final image to a global variable
// can't figure out how to define finalImage as the pinned map
self.myMap = finalImage
} // close snapShotter.start
我已经被困了几天了,所以我当然会感激任何见解。谢谢!
答案 0 :(得分:18)
要使用注释视图呈现image
,您必须在新的图形上下文中手动绘制快照的let rect = self.imageView.bounds
let snapshot = MKMapSnapshotter(options: options)
snapshot.start { snapshot, error in
guard let snapshot = snapshot, error == nil else {
print("\(error)")
return
}
UIGraphicsBeginImageContextWithOptions(options.size, true, 0)
snapshot.image.draw(at: .zero)
let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = pinView.image
var point = snapshot.point(for: location.coordinate)
if rect.contains(point) {
let pinCenterOffset = pinView.centerOffset
point.x -= pinView.bounds.size.width / 2
point.y -= pinView.bounds.size.height / 2
point.x += pinCenterOffset.x
point.y += pinCenterOffset.y
pinImage?.draw(at: point)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// do whatever you want with this image, e.g.
DispatchQueue.main.async {
self.imageView.image = image
}
}
和注释视图.satelliteFlyover
,并从该上下文中获取新图像。在Swift 3中:
class World
{
public:
static Ground* ground;
};
这是改编自https://stackoverflow.com/a/18776723/1271826,它本身改编自WWDC 2013视频Putting MapKit in Perspective。
以下是带有#include "Node.h"
#include "World.h"
void Node::Foo()
{
Ground* ground = World::ground;
}
的快照示例:
答案 1 :(得分:0)
我从Rob的代码中得到一个定义“rect”的错误,因为我的MKMapSnapshotter图像是一个UIImage。但是.bounds是UIImageView的属性,而不是UIImage。因此,rect定义会抛出错误。
以下是我配置选项的方法:
let mapSnapshotOptions = MKMapSnapshotOptions()
// Set the region of the map that is rendered.
let needleLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region = MKCoordinateRegionMakeWithDistance(needleLocation, 1000, 1000)
mapSnapshotOptions.region = region
// Set the scale of the image. We'll just use the scale of the current device, which is 2x scale on Retina screens.
mapSnapshotOptions.scale = UIScreen.main.scale
// Set the size of the image output.
mapSnapshotOptions.size = CGSize(width: 300, height: 300)
// Show buildings and Points of Interest on the snapshot
mapSnapshotOptions.showsBuildings = true
mapSnapshotOptions.showsPointsOfInterest = false
那么还有另一种访问.bounds属性的方法吗?或者我是否错误地创建了快照?