他媽的之前寫了個(gè)app 有動(dòng)態(tài)顯示,我加載圖片用的SDWebImage,占用內(nèi)存那個(gè)高啊在模擬器上看能達(dá)到1.4G 在手機(jī)上就直接閃退,氣死寶寶了 我曹 手機(jī)還發(fā)燙 就跟要爆炸一樣 受不了 啊 搜各種資料才再加上自己的改裝,坑啊 希望能幫助到廣大程序員們
找到第三方的代碼,改改改
//第一步
如圖 UIImage+MultiFormat這個(gè)類里面添加如下壓縮方法
//代碼
+(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;
// 創(chuàng)建一個(gè)bitmap的context
// 并把它設(shè)置成為當(dāng)前正在使用的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)];
}
// 從當(dāng)前context中創(chuàng)建一個(gè)改變大小后的圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當(dāng)前的context出堆棧
UIGraphicsEndImageContext();
return newImage;
}
//第二步-如圖--在下面這個(gè)方法里調(diào)用壓縮方法
//代碼
+ (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方法里面添加代碼
//如圖
//代碼
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];
現(xiàn)在你是不是發(fā)現(xiàn)運(yùn)行內(nèi)存少多了 ?但是圖片都不是高清的,那用戶想看高清的怎么辦? 下面我再奉上自己實(shí)現(xiàn)的三級(jí)緩存的代碼,倒入頭文件,一句代碼調(diào)用
1.倒入頭文件
#import "UIImageView+Additions.h"
2.一句代碼調(diào)用
[_imgView downloadImageWithImageUrlString:圖片地址 placeholderImage:[UIImage imageNamed:@"person.png"]];
下載三級(jí)緩存demol,里面有你想要的
https://github.com/*********/Imitation_SDWebImage.git
下面還有一些其他的作者寫的文章不過用到我的項(xiàng)目中不太好使 不知道適不適用你們
http://www.cocoachina.com/ios/20160530/16495.html
http://www.reibang.com/p/42a29492ebc4