我有一个应用程序使用 MKMapView 来显示 map 。我还有一个 UITableView,其中它在每行的左侧显示 map 的一小段图像。它看起来像这样:
我希望能够从我的 MKMapView 生成左侧的图像。尺寸为 40x40。我知道给定的纬度和经度是我想要获取图像的特定位置的中心。我该怎么做?
最佳答案
获取 View 的快照:
-(UIImage *)pictureForView:(UIView*)view
{
UIGraphicsBeginImageContext(view.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
这是针对整个 View 的——您需要从中切割出您需要的部分。或者也许只是将 map View 置于您需要的位置的中心并进行最大缩放。然后,当将整个 View 的图片调整为缩略图大小时,可能就足够了。
将 map 图像裁剪到所需位置:
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);
关于iphone - 在给定的纬度和经度从 MKMapView 生成 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5556676/