开发者

Rendering MKMapView to UIImage with real resolution

开发者 https://www.devze.com 2023-01-26 07:44 出处:网络
I am using this function for rendering MKMapView instance into image: @implementation UIView (Ext) - (UIImage*) renderToImage

I am using this function for rendering MKMapView instance into image:

@implementation UIView (Ext)
- (UIImage*) renderToImage
{
  UIGraphicsBeginImageContext(self.frame.size);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext(); 
 开发者_如何学JAVA return image;
}

This works fine. But with iphone4 the rendered image doesn't have same resolution as it has really on device. On device I have the 640x920 map view quality, and rendered image has the resolution 320x460. Then I doubled the size that is provided to UIGraphicsBeginImageContext() function but that filled the only top-left image part.

Question: Is there any way to get map rendered to image with full resolution 640x920?


Try using UIGraphicsBeginImageContextWithOptions instead of UIGraphicsBeginImageContext:

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

See QA1703 for more details. It says:

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.


iOS 7 introduced a new method to generate screenshots of a MKMapView. It is now possible to use the new MKMapSnapshot API as follows:

MKMapView *mapView = [..your mapview..]

MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc]init];
options.region = mapView.region;
options.mapType = MKMapTypeStandard;
options.showsBuildings = NO;
options.showsPointsOfInterest = NO;
options.size = CGSizeMake(1000, 500);

MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc]initWithOptions:options];
[snapshotter startWithQueue:dispatch_get_main_queue() completionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
    if( error ) {
        NSLog( @"An error occurred: %@", error );
    } else {
       [UIImagePNGRepresentation( snapshot.image ) writeToFile:@"/Users/<yourAccountName>/map.png" atomically:YES];
    }
}];

Currently all overlays and annotations are not rendered. You have to render them afterwards onto the resulting snapshot image yourself. The provided MKMapSnapshot object has a handy helper method to do the mapping between coordinates and points:

CGPoint point = [snapshot pointForCoordinate:locationCoordinate2D];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号