Rendering MKMapView to UIImage with real resolution

后端 未结 2 1981
长发绾君心
长发绾君心 2020-12-30 12:53

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

@implementation UIView (Ext)
- (UIImage*) renderToImage
{
  UIGraphicsBeginImageContext         


        
相关标签:
2条回答
  • 2020-12-30 13:33

    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.

    0 讨论(0)
  • 2020-12-30 13:51

    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 讨论(0)
提交回复
热议问题