在iOS中,如何将网络图片转换为质量较差的图片?
In iOS, how to convert a web image into a less-quality one?
该应用程序从网络上下载图像并以缩略图的形式在 table 视图中显示。然而,这些图像的质量是"too good"。它们是高清画质,如果 table 视图中的图像太多,可能会稍微减慢 UI 速度。
在我把图片设置到单元格之前,如何制作"less quality"? (占用更少的内存并需要更少的处理能力来显示它们)
我试过这样的事情:
let smallerImage = UIImage(CGImage: image.CGImage!, scale: 0.2, orientation: image.imageOrientation)
但它没有按预期工作。正确的做法是什么?
这是我在 Swift 时代之前的一个旧项目中的工作代码。一个额外的参数 maxLength 传递要使用的最大高度和宽度(对于纵向它是最大高度,对于横向它是最大宽度)。希望您知道如何将 Ojbective-C 翻译成 Swift:
- (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;
}
应用这种缩放确实限制了缩略图消耗的总内存。
该应用程序从网络上下载图像并以缩略图的形式在 table 视图中显示。然而,这些图像的质量是"too good"。它们是高清画质,如果 table 视图中的图像太多,可能会稍微减慢 UI 速度。
在我把图片设置到单元格之前,如何制作"less quality"? (占用更少的内存并需要更少的处理能力来显示它们)
我试过这样的事情:
let smallerImage = UIImage(CGImage: image.CGImage!, scale: 0.2, orientation: image.imageOrientation)
但它没有按预期工作。正确的做法是什么?
这是我在 Swift 时代之前的一个旧项目中的工作代码。一个额外的参数 maxLength 传递要使用的最大高度和宽度(对于纵向它是最大高度,对于横向它是最大宽度)。希望您知道如何将 Ojbective-C 翻译成 Swift:
- (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;
}
应用这种缩放确实限制了缩略图消耗的总内存。