将MKMapView的一部分渲染为图像

Mat*_*eri 6 mapkit mkmapview uipopovercontroller ios

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

谢谢

Apple地图popover

Nat*_*ate 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];
}
Run Code Online (Sandbox Code Playgroud)

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

onButtonTapped方法使用第一种方法捕获地图中心周围的区域,并在屏幕的左上角显示捕获的图像.当然,您可以使用引脚的坐标替换地图中心,根据需要制作区域宽度/高度,并将生成的图像放入弹出视图中.

这只是一个示范.我在我的示例应用程序中使用了一个按钮,只是为了触发捕获,在我想要它之后平移地图.

结果

在此输入图像描述

限制

我的代码只是以1:1的大小比例显示捕获的矩形.当然,如果你愿意的话,你可以将捕获的内容UIImage放到一个可以随意UIImageView缩放的地方.你可以让图像更大.但是,如果你这样做,你将失去图像清晰度.这个过程只是一个屏幕截图UIView.它不能直接对地图数据起作用,因此当你将它炸掉(以更大的尺寸显示图像)时,图像不会像实际放大时那样锐化MKMapView.


dwe*_*ery 4

iOS7可以使用MKMapSnapshotter