ios 加载多张本地图片内存暴增问题解决方法
在使用UICollectionViewCell中加载本地图片会造成界面卡顿,如果只有十几个cell会看不到什么反应,但是如果加载几十上百张的时候就会界面卡顿,这是因为出现了内存暴增的情况,所以现在不能再使用 [UIImage imageNamed:@""]方法了,应该把cell里面的图片进行压缩使用缩略图,这样就会解决界面卡顿,内存也就不会暴增了
cell.m 关键代码
- (void)setModel:(SNZJModel*)model{
_model= model;
// 加载本地图片要把图片变成压缩图,否则会内存暴增
//子线程加载图片
dispatch_async(dispatch_queue_create(0, 0), ^{
UIImage*ima = [UIImageimageNamed:model.pic];//存放图片url图集_picUrlArr
// 压缩图片
UIImage*newImage = [UIImageimageCompressForSize:imatargetSize:CGSizeMake(KHeight(220) /4, ((SCW-KWidth(30) /3)) /4)];
// 在主线程加载图片
dispatch_async(dispatch_get_main_queue(), ^{
self.papImageView.image= newImage;
});
});
}
压缩图片方法
UIImage+SNCompressionImageView.h
#import
NS_ASSUME_NONNULL_BEGIN
@interfaceUIImage(SNCompressionImageView)
+ (UIImage*)imageCompressForSize:(UIImage*)sourceImagetargetSize:(CGSize)size;
@end
NS_ASSUME_NONNULL_END
UIImage+SNCompressionImageView.m
#import "UIImage+SNCompressionImageView.h"
@implementationUIImage(SNCompressionImageView)
+ (UIImage*)imageCompressForSize:(UIImage*)sourceImagetargetSize:(CGSize)size{
UIImage*newImage =nil;
CGSizeimageSize = sourceImage.size;
CGFloatwidth = imageSize.width;
CGFloatheight = imageSize.height;
CGFloattargetWidth = size.width;
CGFloattargetHeight = size.height;
CGFloatscaleFactor =0.0;
CGFloatscaledWidth = targetWidth;
CGFloatscaledHeight = targetHeight;
CGPointthumbnailPoint =CGPointMake(0.0,0.0);
if(CGSizeEqualToSize(imageSize, size) ==NO){
CGFloatwidthFactor = targetWidth / width;
CGFloatheightFactor = targetHeight / height;
if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if(widthFactor > heightFactor){
thumbnailPoint.y= (targetHeight - scaledHeight) *0.5;
}elseif(widthFactor < heightFactor){
thumbnailPoint.x= (targetWidth - scaledWidth) *0.5;
}
}
UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
CGRectthumbnailRect =CGRectZero;
thumbnailRect.origin= thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height= scaledHeight;
[sourceImagedrawInRect:thumbnailRect];
newImage =UIGraphicsGetImageFromCurrentImageContext();
if(newImage ==nil){
NSLog(@"scale image fail");
}
UIGraphicsEndImageContext();
returnnewImage;
}
目前这个方法是管用的,有更好的方法欢迎评论交流