gpt4 book ai didi

iphone - 以最快和最有效的方式调整 UIImage 的大小

转载 作者:太空狗 更新时间:2023-10-30 03:59:41 25 4
gpt4 key购买 nike

我想将 UIImage 的大小调整为一定的宽度和高度,以保持比例不变。最简单的方法是:

 CGSize newSize = CGSizeMake(726, 521);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

上述方法在图像质量和所需时间方面是否有任何缺点?有什么方法比上面的方法更好?

编辑:

这个怎么样:

- (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 ;
}

最佳答案

Image Resizing Techniques 的性能样本中得分是

  • 0.1420 UIKit
  • 0.1722 核心图形
  • 0.1616 图像输入/输出
  • 2.4983 核心图像
  • 2.3126 vImage

所以最快最简单的方法是:


let renderer = UIGraphicsImageRenderer(size: size)
let resized = renderer.image { (context) in
image.draw(in: CGRect(origin: .zero, size: size))
}

Resize a UIImage the right way来自 2009 年,但包含有关插值质量和保持纵横比的有用讨论。


此外,为了将比率保持在最大尺寸范围内:

let image: UIImage = ...
let maxSize = CGSize(width: 726, height: 521)
let newSize = AVMakeRect(aspectRatio: image.size, insideRect: CGRect(origin: .zero, size: maxSize)).size
let resized = UIGraphicsImageRenderer(size: newSize).image { _ in
image.draw(in: CGRect(origin: .zero, size: newSize))
}

更改每点像素密度(默认为当前屏幕的 ppp):

let format = UIGraphicsImageRendererFormat()
format.scale = 1
UIGraphicsImageRenderer(size: newSize, format: format)
...

关于iphone - 以最快和最有效的方式调整 UIImage 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7522159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com