1

我有一个大小为3264 × 2448的图像和一个大小为768 × 1024的图像视图。我想在不损失图像质量的情况下获得与视图大小相等的图像大小。

我用谷歌搜索了它;AspectFit没有给我适当的输出。我尝试了以下代码:

- (UIImage *)imageByScalingProportionallyToSize: (CGSize)targetSize {

   UIImage *sourceImage = self;
   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;
        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;
       }
    }


    // this is actually the interesting part:

    UIGraphicsBeginImageContext(targetSize);

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

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if(newImage == nil) NSLog(@"could not scale image");


    return newImage ;
}
4

3 回答 3

1

请尝试以下代码:

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

   return newImage;
}

将您的新尺寸指定为 (768,1024) 并传递您的原始图像,但请确保原始图像的高度和宽度比例应与转换后的图像比例相同。

于 2013-06-26T12:58:12.450 回答
0

我使用这篇文章作为我的一些项目的参考,包括图像调整大小。UIImage+Resize 类别工作得很好,除了在创建调整大小的图像版本之前对性能造成重大影响。

您可以在磁盘上缓存调整大小的版本,以避免将来再次调整大小。另外我还没有尝试过,但您可以尝试在后台线程中调整图像大小以避免阻塞 UI。

于 2013-06-26T12:17:36.557 回答
0

输入图像的尺寸不是您UIImageView的尺寸的倍数,这就是为什么 aspectFit 在这里不起作用(很可能会在两侧留下间隙)。如果您使用 scaleToFill,您的图像会变形,因为您的图像尺寸再次关闭。我认为您必须对其中一个的尺寸做一些事情才能正确保存图像。

于 2013-06-26T12:17:46.687 回答