2011-04-05 35 views
4

我有一個應用程序,它使用MKMapView來顯示地圖。我還有一個UITableView,它在每行左側顯示地圖的小片段圖像。它看起來是這樣的:在給定的經度和緯度從MKMapView生成UIImage

enter image description here

我希望能夠生成圖像,從我的MKMapView左側。尺寸是40x40。我知道給定的緯度和經度是我想要獲得圖像的特定位置的中心。我該怎麼做呢?

回答

5

如果想獲得視圖的快照:

-(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); 
+0

我知道如何讓整個來看,我不知道是如何獲得在緯度爲中心的說50 * 50像素的圖片,長 – aherlambang 2011-04-05 18:41:34

+0

或者我該如何將這個巨大的圖像轉換爲50x50像素?我不是在談論調整大小,而是裁剪中間到50 * 50 – aherlambang 2011-04-05 18:43:05

+0

對不起40x40,因爲單元格圖像大小是40x40 – aherlambang 2011-04-05 18:51:00

相關問題