这是我从斯威夫特时代之前的一个旧项目的工作代码。一个额外的参数maxLength传递最大高度和宽度来使用(纵向是最大高度,横向是最大宽度)。希望你知道怎么翻译从Ojbective-C斯威夫特:
- (UIImage *) scaleImage: (UIImage *) image toMax: (float) maxLength
{
//scale down image to fit withing square of maxLength x maxLength
CGSize size = image.size;
printf("scaleImage source size: %f, %f\n", size.width, size.height);
float scaleX = size.width/maxLength;
float scaleY = size.height/maxLength;
float scale = scaleX > scaleY ? scaleX : scaleY;
int newWidth = round(size.width/scale);
int newHeight = round(size.height/scale);
CGSize newSize = CGSizeMake(size.width/scale, size.height/scale);
printf("scaleImage new size: %d, %d\n", newWidth, newHeight);
UIGraphicsBeginImageContext(newSize);// a CGSize that has the size you want
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//image is the original UIImage
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
应用这种缩放确实限制由缩略图所消耗的总内存。
您应该首先尝试下载更适合显示尺寸的图像,否则会浪费用户的细胞数据。 – jtbandes
@jtbandes下载的图像不是由我安排的。它们就像它们一样,我想渲染这些图像。 –
下采样将使用更多的CPU资源比显示更高分辨率的图像 –