I am trying to create a snapshot of a MKMapView in iOS7 application the same way it's recommended everywhere for previous iOS versions:
- (UIImage*) renderMapViewToImage
{
UIGraphicsBeginImageContextWithOptions(mapView.frame.size, NO, 0.0);
[mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
However, the image returned is a black rectangle with a blue current location dot on top of it. I've tried using different sublayers of the mapView as well, but the result is always the same.
Does anyone know how to take MKMapView snapshots in iOS7 ?
For Swift 3
Here is a swift 3 version I modified from this article: Render a Map as an Image using MapKit
The following code allows you to snapshot a region based on both Point(1 coordinate) and Polyline(several coordinates)
You can use
MKMapSnapshotter
and grab theimage
from the resultingMKMapSnapshot
. See the discussion of it WWDC 2013 session video, Putting Map Kit in Perspective.For example:
Having said that, the
renderInContext
solution still works for me. There are notes about only doing that in the main queue in iOS7, but it still seems to work. ButMKMapSnapshotter
seems like the more appropriate solution for iOS7.If you want to include some annotations in the snapshot, you have to draw them manually (!). This is discussed in some detail at the end of the Putting Map Kit in Perspective video. I have to say that this is one of the least elegant implementations that I've ever seen Apple advise. Anyway, in iOS, it might look like:
For MacOS implementation, see that video for more information, but the technique is basically the same (the mechanism for creating the images is slightly different).
For iOS 10 and above you can use
UIGraphicsImageRenderer
class for rendering any view to image (just in case if you don't want to useMKMapSnapshotter
, since i am usingMapBox
).Result: