generate UIImage from MKMapView at a given latitude and longitude
I have an app that uses MKMapView to display a map. I also have a UITableView in which it displays a smal开发者_运维问答l snippet image of the map to the left of each rows. It looks something like this:
I want to be able to generate that image to the left from my MKMapView. The size is 40x40. I know the given latitude and longitude as the center of a particular location where I want to get the image. How do I do this?
To get a snapshot of a view:
-(UIImage *)pictureForView:(UIView*)view
{
UIGraphicsBeginImageContext(view.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
That's for the whole view - you'll need to carve the piece you need out of it. Or maybe just center the map view on the location you need and do the maximum zoom. Then the picture of the whole view, when resized to a thumbnail size, might be just good enough.
To crop the map image to the desired location:
UIImage* mapImage = [self pictureForView:self.mapView];
MKCoordinateRegion mapRegion = self.mapView.region;
//pointOfInterest is assumed to be on the map view, e.g. get the coordinate of the pin
CLLocationCoordinate2D pointOfInterest = ????;
double mapLatFrom = mapRegion.center.latitude - mapRegion.span.latitudeDelta/2;
double mapLonFrom = mapRegion.center.longitude - mapRegion.span.longitudeDelta/2;
double cropX = ((pointOfInterest.latitude - mapLatFrom)/mapRegion.span.latitudeDelta)*mapView.frame.size.width - self.imageView.frame.size.width /2;
double cropY = ((pointOfInterest.longitude - mapLonFrom)/mapRegion.span.longitudeDelta)*mapView.frame.size.height - self.imageView.frame.size.height /2;
CGRect cropRect = CGRectMake(cropX, cropY, self.imageView.frame.size.width, self.imageView.frame.size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([mapImage CGImage], cropRect);
self.imageView.image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
精彩评论