【问题标题】:How to add image from url to MKAnnotationView for retina display?如何将图像从 url 添加到 MKAnnotationView 以进行视网膜显示?
【发布时间】:2012-08-13 22:51:06
【问题描述】:

我正在尝试使用来自 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;
}

您会在 Retina 显示器上看到非常像素化的图像。

有什么建议吗? 谢谢

【问题讨论】:

    标签: objective-c cocoa-touch mapkit mkannotation mkannotationview


    【解决方案1】:

    要点是这样...

    1. 使用[[UIScreen mainScreen] scale] 向您的服务器请求标准或@2x 图像。
    2. NSData 创建一个CGImageRef
    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);
    

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

    【讨论】:

    • 我已经用一些工作代码示例更新了我的答案。请注意,使用 ARC 需要在第 5 行进行 __bridge 转换,否则不需要。
    • 非常感谢!我真的很想知道为什么没有相应的 UIImage 方法来使用特定的比例因子进行初始化......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    相关资源
    最近更新 更多