我有一个应用程序使用mkmappview来显示地图。我还有一个uitableview,它在每行的左边显示地图的一个小片段图像。看起来像这样:
我希望能够从我的mkmappview生成左边的图像。尺寸是40x40。我知道给定的经纬度是我想要得到图像的特定位置的中心。我该怎么做?
最佳答案
要获取视图的快照,请执行以下操作:
-(UIImage *)pictureForView:(UIView*)view
{
UIGraphicsBeginImageContext(view.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
这是整个视图-你需要从中雕刻出你需要的部分。或者只是把地图视图放在你需要的位置,做最大的缩放。然后,当调整到缩略图大小时,整个视图的图片可能就足够了。
要将地图图像裁剪到所需位置:
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);