像 iMessage 一样有 URL 表示位置的缩略图最好吗?

What is the best to have URL like thumbnail indicating the location like iMessage?

我需要一个可点击的缩略图来指示位置,就像 iMessage 一样,实现它的最佳方法是什么?

您可以将 MKMapView 添加到您的 table 单元格,但更好的方法是使用 MKSnapshotter 创建快照并将它们添加到您的单元格。

来自 NSHipster 的博客 post here,从 MKMapSnapshotter 检索图像的示例代码是:

MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
options.region = self.mapView.region;
options.size = self.mapView.frame.size;
options.scale = [[UIScreen mainScreen] scale];

NSURL *fileURL = [NSURL fileURLWithPath:@"path/to/snapshot.png"];

MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
[snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
    if (error) {
        NSLog(@"[Error] %@", error);
        return;
    }

    UIImage *image = snapshot.image;
    NSData *data = UIImagePNGRepresentation(image);
    [data writeToURL:fileURL atomically:YES];
}];

options 传递给这里的快照是MKMapSnapshotOptions。阅读博客以获取更多信息和完整教程。

MKMapSnapshotter 也足够灵活,可以向快照添加 default/custom 注释,正如您在问题中 post 编辑的那样。

来自同一来源的示例代码,注释为:

[snapshotter startWithQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
              completionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
      if (error) {
          NSLog(@"[Error] %@", error);
          return;
      }

      MKAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:nil reuseIdentifier:nil];

      UIImage *image = snapshot.image;
      UIGraphicsBeginImageContextWithOptions(image.size, YES, image.scale);
      {
          [image drawAtPoint:CGPointMake(0.0f, 0.0f)];

          CGRect rect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
          for (id <MKAnnotation> annotation in self.mapView.annotations) {
              CGPoint point = [snapshot pointForCoordinate:annotation.coordinate];
              if (CGRectContainsPoint(rect, point)) {
                  point.x = point.x + pin.centerOffset.x -
                                (pin.bounds.size.width / 2.0f);
                  point.y = point.y + pin.centerOffset.y -
                                (pin.bounds.size.height / 2.0f);
                  [pin.image drawAtPoint:point];
              }
          }

          UIImage *compositeImage = UIGraphicsGetImageFromCurrentImageContext();
          NSData *data = UIImagePNGRepresentation(compositeImage);
          [data writeToURL:fileURL atomically:YES];
      }
      UIGraphicsEndImageContext();
}];

这里要注意的是,您必须使用自定义代码从快照创建图像。

生成快照后,您可以在单元格内绘制它。

如果您想进一步优化这一点,可以将生成的快照保存在本地存储中,并将其用于相同坐标的单元格重用,而不是每次重用单元格时都生成图像。

阅读 MKMapSnapshotter HERE, and MKSnapshotOptions HERE 的官方文档。