他妈的之前写了个app 有动态显示,我加载图片用的SDWebImage,占用内存那个高啊在模拟器上看能达到1.4G 在手机上就直接闪退,气死宝宝了 我曹 手机还发烫 就跟要爆炸一样 受不了 啊 搜各种资料才再加上自己的改装,坑啊 希望能帮助到广大程序员们
找到第三方的代码,改改改
//第一步
如图 UIImage+MultiFormat这个类里面添加如下压缩方法
CC701F69-548C-49D8-BAB7-BCCF18CAEB83.png
//代码
+(UIImage *)compressImageWith:(UIImage *)image
{
float imageWidth = image.size.width;
float imageHeight = image.size.height;
float width = 320;
float height = image.size.height/(image.size.width/width);
float widthScale = imageWidth /width;
float heightScale = imageHeight /height;
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(CGSizeMake(width, height));
if (widthScale > heightScale) {
[image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
}
else {
[image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
}
// 从当前context中创建一个改变大小后的图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
return newImage;
}
//第二步-如图--在下面这个方法里调用压缩方法
199FDE83-92A8-439C-AFE6-784B947077C5.png//代码
+ (UIImage *)sd_imageWithData:(NSData *)data {
UIImage *image;
NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
if ([imageContentType isEqualToString:@"image/gif"]) {
image = [UIImage sd_animatedGIFWithData:data];
}
#ifdef SD_WEBP
else if ([imageContentType isEqualToString:@"image/webp"])
{
image = [UIImage sd_imageWithWebPData:data];
}
#endif
else {
image = [[UIImage alloc] initWithData:data];
if (data.length/1024 > 90) {
image = [self compressImageWith:image];
}
UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
if (orientation != UIImageOrientationUp) {
image = [UIImage imageWithCGImage:image.CGImage
scale:image.scale
orientation:orientation];
}
}
return image;
}
//第三步,在SDWebImageDownloaderOperation的connectionDidFinishLoading方法里面添加代码
//如图
19AA2B70-4361-445A-83E5-49B54E40970D.png
//代码
UIImage *image = [UIImage sd_imageWithData:self.imageData];
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
image = [self scaledImageForKey:key image:image];
NSData *data = UIImageJPEGRepresentation(image, 1);
self.imageData = [NSMutableData dataWithData:data];
现在你是不是发现运行内存少多了 ?但是图片都不是高清的,那用户想看高清的怎么办? 下面我再奉上自己实现的三级缓存的代码,倒入头文件,一句代码调用
1.倒入头文件
#import "UIImageView+Additions.h"
2.一句代码调用
[_imgView downloadImageWithImageUrlString:图片地址 placeholderImage:[UIImage imageNamed:@"person.png"]];
下载三级缓存demol,里面有你想要的
https://github.com/*********/Imitation_SDWebImage.git
下面还有一些其他的作者写的文章不过用到我的项目中不太好使 不知道适不适用你们
http://www.cocoachina.com/ios/20160530/16495.html
http://www.jianshu.com/p/42a29492ebc4
网友评论