實(shí)現(xiàn)方案來(lái)自度娘
1.在SDWebImage目錄下的 UIImage+MultiFormat.m 文件中增加方法
+ (UIImage *)compressImageWith:(UIImage *)image {
float imageWidth = image.size.width;
float imageHeight = image.size.height;
float width = 640;
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;
}
2.在該文件下面方法中調(diào)用
+ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data {
if (!data) { return nil; }
UIImage *image;
SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data];
if (imageFormat == SDImageFormatGIF) {
image = [UIImage sd_animatedGIFWithData:data];
}
#ifdef SD_WEBP
else if (imageFormat == SDImageFormatWebP) {
image = [UIImage sd_imageWithWebPData:data];
}
#endif
else {
image = [[UIImage alloc] initWithData:data];
//在這里增加下面三行代碼
if (data.length/1024 > 128) {
image = [self compressImageWith:image];
}
#if SD_UIKIT || SD_WATCH
UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
if (orientation != UIImageOrientationUp) {
image = [UIImage imageWithCGImage:image.CGImage
scale:image.scale orientation:orientation];
}
#endif
}
return image;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。