Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a UIImage from a MKMapView

Tags:

ios

mapkit

I want to create a UIImage from a MKMapView. My map is correctly displayed in the view, however the UIImage produced is just a gray image. Here's the relevant snippet.

UIGraphicsBeginImageContext(mapView.bounds.size);
[mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
mapImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Anyone know how to make a UIImage using MapKit?

like image 365
Loren Olson Avatar asked Nov 11 '10 21:11

Loren Olson


2 Answers

Here is the improved function for retina display:

@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;
}
like image 188
Krešimir Prcela Avatar answered Dec 09 '22 20:12

Krešimir Prcela


On iOS7, there is a new API on MapKit for this called MKMapSnapshotter. So you actually don't need to create a mapview, load the tiles and create a graphic context capturing yourself.

Take a look into it at https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKMapSnapshotter_class/Reference/Reference.html

like image 32
DZenBot Avatar answered Dec 09 '22 19:12

DZenBot