从服务器调整和放置Retina UIImage

时间:2014-02-13 01:29:10

标签: ios uiimage retina-display uigraphicscontext

我知道之前已经问过这个......但是我觉得我做的一切都很好但是在视网膜显示屏上看起来并不好看。我听说如果需要在视网膜上显示UIImage,我所要做的就是将比例设置为2.0。但仍然没有工作我不知道UIGraphics调整大小和裁剪是否会影响图像的质量。通常我会从自定义类UIImageView中的setImage调用我的resizer(来自服务器的图像,它具有正确的宽度,但更高,所以它假设只能裁剪)在我的控制器中就像这样调用它:

[customUIImageViewInstance setImage:[UIImage imageWithData:[impreso thumb] scale:isRetina()?2:1]];

在我的自定义UIImageView实现中:

-(void)setImage:(UIImage *)image{
    if (image==nil) {
        [super setImage:nil];
    }else{
        [super setImage:[self scaleAnImageAspectFillCropHeight:image withNewWide:self.frame.size.width andNewTall:self.frame.size.height]];
    }
}



-(UIImage*) scaleAnImageAspectFillCropHeight:(UIImage*) image withNewWide:(NSUInteger) wide andNewTall:(NSUInteger) tall{
    if (image.size.width!=wide || image.size.height!=tall){
        BOOL retina;
        if ([image scale]==2) {
            retina = YES;
            wide*=2;
            tall*=2;
        }else{
            retina = NO;
        }
        CGFloat width = image.size.width;
        CGFloat height = image.size.height;
        CGFloat targetWidth = wide;
        CGFloat targetHeight = tall;
        CGFloat scaleFactor = 0.0;
        CGFloat scaledWidth;
        CGFloat scaledHeight;
        CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    CGFloat widthFactor = targetWidth / width;
    CGFloat heightFactor = targetHeight / height;

    scaleFactor = widthFactor; // the width must be all visible, the height might be cropped but that is the inteded behavior

    scaledWidth  = width * scaleFactor;
    scaledHeight = height * scaleFactor;

    // centers X if needed, Y starts in 0 because the top part of the image is important
    thumbnailPoint.y = 0;
    if (widthFactor < heightFactor){
        thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
    }


    UIGraphicsBeginImageContext(CGSizeMake(wide, tall)); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [image drawInRect:thumbnailRect];

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    if (retina) {
        newImage = [UIImage imageWithCGImage:newImage.CGImage scale:2 orientation:newImage.imageOrientation];
    }

    if(newImage == nil){
        [self setContentMode:UIViewContentModeScaleAspectFit];
    }else{
        //pop the context to get back to the default
        UIGraphicsEndImageContext();
        return newImage;
    }
}
return image;
}

我一直在调试...这个尺寸和尺度是正确的。我不知道是什么搞乱了图像的质量。一个简单的解释将有很多帮助,thx。

1 个答案:

答案 0 :(得分:1)

您是否尝试将任何图像强制缩放两次以进行视网膜显示?如果是,图像的质量不会变得更好。这很合理。您可能知道,通过简单地拉伸宽度和高度,图像质量 NOT 得到改善。

您真正需要做的是使用最初具有两倍分辨率的高分辨率图像。