如何将大图像缩小并保持与原始图像相同的良好质量?

4

我正在使用大小为80X80的imagview来显示大图像(1024 X 780)。

将大图像放入imageview时,图像看起来被挤压,压缩,不像高质量的图像。

我的问题是,如何使大图像变小,同时保持与原始图像一样的高质量?

5个回答

1
在这种情况下,您应该对想要在ImageView中显示的图像进行适当的缩放。
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize 
{
    UIImage *sourceImage = chosenImage;
    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

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

        if (widthFactor < heightFactor) 
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;

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

        // center the image

        if (widthFactor < heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }


    UIGraphicsBeginImageContext(targetSize);

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

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage ;
}

谢谢,Surya。这段代码很有用,符合我的理念。 - Durga

1
在图像视图中,请将 imageview.mode 设置为 centre 而不是 scale to fit 或其他任何模式。 我相信这会使您的任何缩放图像以最佳质量显示在 80x80 的尺寸中。

1

谢谢,Surya。这段代码很有用,有助于我的理解。 - Durga

0

从1034x780缩放到80x80几乎不可能保持质量,因为没有足够的空间来捕获所有细节。

您可以尝试进行缩放:

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

这个可以运行,但在iOS5.0.1上会导致内存泄漏。有没有其他的方法?https://dev59.com/Imsy5IYBdhLWcg3w6iNZ - David

0

您可以设置图像模式 [imageView setContentMode:UIViewContentModeScaleAspectFill]; imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ); [imageView setClipsToBounds:YES];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接