3

我正在尝试使用来自 url 的图像创建自定义 MKAnnotationView。

发生的情况是,当设备具有视网膜显示时,MKAnnotationView 的图像会变得模糊,因为它的分辨率会加倍。

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

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

您将在视网膜显示器上看到图像非常像素化。

有什么建议该怎么做吗?谢谢

4

1 回答 1

5

要点是这样...

  1. 用于[[UIScreen mainScreen] scale]向您的服务器询问标准或@2x 图像。
  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);

请注意,鉴于我的代码的前两行,您需要在服务器上拥有两种图像分辨率。目前图像在视网膜上会显得更小,在非视网膜屏幕上会更大。

于 2012-08-20T07:37:51.067 回答