Generate UIImage from MKMapView at a given latitude and longitude

I have an application that uses MKMapView to display a map. I also have a UITableView in which it displays a small image at the bottom of the map to the left of each row. It looks something like this:

enter image description here

I want to be able to generate this image to the left of my MKMapView. Size 40x40. I know the given latitude and longitude as the center of a specific place where I want to get an image. How to do it?

+4
source share
1 answer

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; } 

What for the whole presentation - you need to cut out the piece that you need. Or maybe just focus the map in the right place and make the maximum increase. Then the image of the whole view when resizing the thumbnail can be quite good.

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, eg 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); 
+5
source

Source: https://habr.com/ru/post/1346787/


All Articles