如何在OS X中打印MKMapView?

时间:2014-08-28 21:30:58

标签: cocoa printing mkmapview mapkit nsprintoperation

发送MKMapView -print:条消息会产生仅包含+/-按钮和“合法”链接的输出。如果我尝试[NSPrintOperation printOperationWithView:someMKMapView][theWindowThatContainsAMapView print][[NSPrintOperation PDFOperationWithView:someMKMapView insideRect:someMKMapView.bounds toPath:@"foo.pdf" printInfo:nil] runOperation],则相同。

Apple自己的Maps.app会打印地图,顺便说一句。

有没有人设法打印MKMapView?

1 个答案:

答案 0 :(得分:3)

魔法类是MKMapSnapshotter

假设有一个MKMapView实例mapView,这是一个简单的例子,用于创建MKMapView当前内容的图像作为用Swift编写的TIFF文件。 此图像可打印。

let options = MKMapSnapshotOptions()
options.region = mapView.region;
options.size = mapView.frame.size;

let fileURL = NSURL(fileURLWithPath:"/path/to/snapshot.tif")
let mapSnapshotter = MKMapSnapshotter(options: options)
mapSnapshotter.startWithCompletionHandler { (snapshot, error) -> Void in
  // do error handling
  let image = snapshot.image
  if let data = image.TIFFRepresentation {
    data.writeToURL(fileURL!, atomically:true)
  } else {
    println("could not create TIFF data")
  }
}

修改:

打印而不是创建文件

let options = MKMapSnapshotOptions()
options.region = mapView.region;
options.size = mapView.frame.size;

let mapSnapshotter = MKMapSnapshotter(options: options)
mapSnapshotter.startWithCompletionHandler { (snapshot, error) -> Void in
  // do error handling
  let image = snapshot.image
  let imageView = NSImageView()
  imageView.frame = NSRect(origin: NSZeroPoint, size: image.size)
  imageView.image = image

  let info = NSPrintInfo.sharedPrintInfo()
  info.horizontalPagination = .FitPagination
  info.verticalPagination = .FitPagination
  let operation = NSPrintOperation(view: imageView, printInfo:info)
  operation.showsPrintPanel = true
  operation.runOperation()