我有一张尺寸 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 ;
}
答案 0 :(得分:0)
我使用this文章作为我的一些项目的参考,包括图像大小调整。 UIImage + Resize类别的效果非常好,除非在创建调整大小的图像版本之前会有显着的性能影响。
您可以将已调整大小的版本缓存在磁盘上,以避免将来再次调整大小。此外,我还没有尝试,但您可以尝试在后台线程中调整图像大小以避免阻止UI。
答案 1 :(得分:0)
输入图像的尺寸不是UIImageView
尺寸的倍数,这就是为什么aspectFit在这里不起作用(最有可能在两侧留下间隙)。如果您使用scaleToFill,您的图像将会变形,因为您的图像尺寸再次关闭。我认为你必须对其中一个的尺寸做些什么才能正确保存图像。
答案 2 :(得分:0)
请尝试以下代码:
+ (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)并传递原始图像,但请确保原始图像的高度和宽度比率与转换后的图像比率相同。