Rendering MKMapView to UIImage with real resolution

后端 未结 2 1986
长发绾君心
长发绾君心 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: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//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];
    

提交回复
热议问题