如何将图像从url添加到MKAnnotationView进行视网膜显示?

ozb*_*zba 3 cocoa-touch objective-c mapkit mkannotation mkannotationview

我正在尝试使用来自网址的图片创建自定义MKAnnotationView.

当设备具有视网膜显示时,MKAnnotationView的图像模糊,因为它的分辨率加倍.

如果图像来自应用程序,它将加载@ 2x图像(如果存在),但如果您从这样的网址设置图像,例如:

- (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id ) annotation    
{
MKAnnotationView *customAnnotationView=[[MKAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:nil];

NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:@"http://www.interaction-design.org/images/icons/play-button-red-300x300.png"]];


UIImage *img = [UIImage imageWithData:imageData];
[customAnnotationView setImage:img ];
return customAnnotationView;
}
Run Code Online (Sandbox Code Playgroud)

你会看到视网膜显示器上的图像非常像素化.

有什么建议吗?谢谢

Jes*_*edc 5

要点就是......

  1. 使用[[UIScreen mainScreen] scale]要求服务器的标准或@ 2倍的图像.
  2. CGImageRef从中创建一个NSData
  3. 使用CGImageRef并[[UIScreen mainScreen] scale]创建一个UIImage

执行此操作的代码如下所示:

NSString *imagePath = @"http://www.interaction-design.org/images/icons/play-button-red-300x300";
imagePath = [imagePath stringByAppendingString:[[UIScreen mainScreen] scale] > 1 ? @"@2x.png": @".png"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imagePath]];

CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)imageData);
CGImageRef imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO, kCGRenderingIntentDefault);
UIImage *image = [UIImage imageWithCGImage:imageRef scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp];

CGDataProviderRelease(dataProvider);
CGImageRelease(imageRef);
Run Code Online (Sandbox Code Playgroud)

请注意,在我的代码的前两行中,您需要在服务器上具有两个图像分辨率.目前,图像在视网膜上看起来更小,在非视网膜屏幕上更大.