6

我有兴趣捕获地图的一部分以创建您在弹出窗口顶部看到的图像。我想我会捕获一个 UIImage,你可以从图钉的坐标开始吗?

谢谢

苹果地图弹出框

4

2 回答 2

5

你可以尝试这样的事情:

- (UIImage*) imageFromView:(UIView*)view rect:(CGRect)rect {
    // capture the full view in an image
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* viewImg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    // crop down to just our desired rectangle, accounting for Retina scale 
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGRect scaledRect = CGRectMake(scale * rect.origin.x, scale * rect.origin.y,
                                   scale * rect.size.width, scale * rect.size.height);
    CGImageRef resultImgRef = CGImageCreateWithImageInRect([viewImg CGImage], scaledRect);
    UIImage* result = [UIImage imageWithCGImage: resultImgRef
                                          scale: 1.0f / scale
                                    orientation: UIImageOrientationUp];

    CGImageRelease(resultImgRef);
    return result;
}

- (IBAction)onButtonTapped:(id)sender {
    // just pick the map's center as the location to capture.  could be anything.
    CLLocationCoordinate2D center = self.map.centerCoordinate;
    // convert geo coordinates to screen (view) coordinates
    CGPoint point = [self.map convertCoordinate:center toPointToView: self.map];

    // make this span whatever you want - I use 120x80 points
    float width = 120.0;
    float height = 80.0;
    // here's the frame in which we'll capture the underlying map
    CGRect frame = CGRectMake(point.x - width / 2.0,
                              point.y - height / 2.0,
                              width, height);

    // just show the captured image in a UIImageView overlay 
    //  in the top, left corner, with 1:1 scale
    UIImageView* overlay = [[UIImageView alloc] initWithImage: [self imageFromView: self.map rect: frame]];
    frame.origin = CGPointZero;
    overlay.frame = frame;
    [self.view addSubview: overlay];
}

imageFromView:rect:方法仅在给定视图中捕获给定的矩形区域,并生成一个UIImage.

onButtonTapped方法使用第一种方法捕获我的地图中心周围的区域,并将捕获的图像显示在屏幕的左上角。当然,您可以用图钉的坐标替换地图中心,使区域宽度/高度随心所欲,然后将生成的图像放入弹出视图中。

这只是一个演示。在将地图平移到我想要的位置后,我在示例应用程序中使用了一个按钮来触发捕获。

结果

在此处输入图像描述

限制

我的代码只是以 1:1 的大小比例显示捕获的矩形。当然,如果您愿意,您可以将捕获的内容UIImage放入一个可以随意UIImageView缩放的文件中。您可以将图像放大。但是,如果这样做,您将失去图像清晰度。此过程仅对UIView. 它不能直接处理地图数据,所以当你放大它(以更大的尺寸显示图像)时,图像不会像你实际放大MKMapView.

于 2013-02-05T06:01:53.973 回答
4

iOS7可以使用MKMapSnapshotter

于 2013-11-07T23:11:11.023 回答