gpt4 book ai didi

iphone - 应用程序在UIScrollview中加载太多图像时崩溃

转载 作者:行者123 更新时间:2023-12-03 15:56:31 26 4
gpt4 key购买 nike

我正在创建一个应用程序,该应用程序加载了56张图像,总大小约为200MB,当我在UIScrollView中显示所有这些图像时,该应用程序花费的时间太长(大约6分钟),有时会崩溃。

请为我提供一种使用UIView进行排序并一次加载1张图片的方法。图像保存在应用程序中。

最佳答案

如果您的图像 View 大小为320 * 416像素,则计算内存大小可能为320 * 416 * 200/1000000 =〜27 MB。

更好的选择是将图像缩放到320 * 416像素:

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

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

关于iphone - 应用程序在UIScrollview中加载太多图像时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12005935/

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