1

I want to take a screenshot of a MapView and save to photos

This is the used source:

- (IBAction)screenshot:(id)sender {



if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(mapView.frame.size, NO, [UIScreen mainScreen].scale);

else


UIGraphicsBeginImageContext(mapView.frame.size);
[mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

}

The action is successful, but the photo looks like this here MapView Screenshot

I do not know what is wrong. I've already tried some codes. All with the same result. If I make a screenshot of the entire view, the map also looks like the picture above.

Does anyone have any idea or can help me?

  • [Here is another answer maybe can solve your problem](https://stackoverflow.com/questions/18776288/snapshot-of-mkmapview-in-ios7) – 刘俊利 Jul 20 '19 at 08:39

1 Answers1

0

EDIT:

 - (UIImage*) ImageFromMapView
{
  UIGraphicsBeginImageContext(self.frame.size);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  //[[[yourmapView.layer sublayers] objectAtIndex:1] renderInContext:UIGraphicsGetCurrentContext()];  try this upper fails
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();  
  return image;
}

Try using UIGraphicsBeginImageContextWithOptions instead of UIGraphicsBeginImageContext:

 UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);

Note: Starting from iOS 4, UIGraphicsBeginImageContextWithOptions allows you to provide with a scale factor. A scale factor of zero sets it to the scale factor of the device's main screen. This enables you to get the sharpest, highest-resolustion snapshot of the display, including a Retina Display.

Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • I have changed the Code to: if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) UIGraphicsBeginImageContextWithOptions(mapView.frame.size, NO, 0.0); // [UIScreen mainScreen].scale); else UIGraphicsBeginImageContextWithOptions(mapView.frame.size, NO, 0.0); [mapView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil); But its always the same result. :-( – user1493720 Jul 01 '12 at 12:21
  • Looks like it's still an error -- Can't grab a saved image of MKMapView. – jmstone617 Oct 16 '12 at 05:12
  • The edit does not change anything. After some experimentation and more SO surfing, two things need to happen: 1) You need to save the image in MKMapView's mapViewDidFinishLoading delegate method. It also looks like after this method is called, you need to perform the save after a delay of 1-2 seconds – jmstone617 Oct 16 '12 at 15:01