Ios 从MKMapView生成UIImage
我想从Ios 从MKMapView生成UIImage,ios,mapkit,Ios,Mapkit,我想从MKMapView创建UIImage。我的地图在视图中正确显示,但是生成的UIImage只是一个灰色图像。下面是相关的片段 UIGraphicsBeginImageContext(mapView.bounds.size); [mapView.layer renderInContext:UIGraphicsGetCurrentContext()]; mapImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndIma
MKMapView
创建UIImage
。我的地图在视图中正确显示,但是生成的UIImage
只是一个灰色图像。下面是相关的片段
UIGraphicsBeginImageContext(mapView.bounds.size);
[mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
mapImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
任何人都知道如何使用MapKit制作
UIImage
?如果在初始化地图后立即调用此选项(可能在viewDidLoad?),则可能会得到灰色图像,因为地图尚未绘制完成
尝试:
- 使用performSelector:withObject:afterDelay:使用短延迟调用捕获代码(即使是0秒也可以工作,因此它会在当前方法完成后立即触发)
- 如果要添加批注,请在didAddAnnotationViews委托方法中调用捕获代码
在模拟器上,使用performSelector,零延迟工作。在设备上,需要更长的延迟(约5秒)
但是,如果添加注释(并在didAddAnnotationViews方法中捕获),它会立即在模拟器和设备上工作。嘿,Loren。地图视图中有多个图层。我认为第一个是地图,第二个是谷歌图层。他们可能在3.1之后更改了mapkit中的某些内容。你可以试试
[[[mapView.layer sublayers] objectAtIndex:1] renderInContext:UIGraphicsGetCurrentContext()];
你也可以试试
CGRect rect = [mapView bounds];
CGImageRef mapImage = [mapView createSnapshotWithRect:rect];
希望这能有所帮助。我使用的代码与ios sdk 4.1测试的代码相同,工作正常。因此,当地图已显示给用户并用户按下按钮时,此操作将被调用:
UIImage *image = [mapView renderToImage];
以下是作为UIView扩展实现的包装函数:
- (UIImage*) renderToImage
{
UIGraphicsBeginImageContext(self.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
所以,问题不在代码部分 以下是视网膜显示的改进功能:
@implementation UIView (Ext)
- (UIImage*) renderToImage
{
// IMPORTANT: using weak link on UIKit
if(UIGraphicsBeginImageContextWithOptions != NULL)
{
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(self.frame.size);
}
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
在iOS7上,MapKit上有一个新的API,名为MKMapSnapshotter。因此,您实际上不需要创建地图视图、加载平铺并创建图形上下文来捕获自己
查看一下注意,mapView可能无法完成加载,因此图像可能是灰色的。 作为 不会总是被调用,您应该在
mapViewDidFinishRenderingMap:fullyRendered:
代码就是这样的
- (UIImage *)renderToImage:(MKMapView *)mapView
{
UIGraphicsBeginImageContext(mapView.bounds.size);
[mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
我认为这不是问题所在。我等待地图加载,它在视图中,看起来还可以。这对我来说很有效(同样在4.1上)。您是否尝试过通过按下按钮来调用捕获,以查看是否是时间问题或其他问题?
- (UIImage *)renderToImage:(MKMapView *)mapView
{
UIGraphicsBeginImageContext(mapView.bounds.size);
[mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}