手機(jī)中經(jīng)常會(huì)遇到一些非常大的圖片,當(dāng)把它們導(dǎo)入到我們的緩存時(shí)有時(shí)會(huì)造成程序的閃退,即超過(guò)了125mb,此時(shí)我們有三種方法對(duì)圖片進(jìn)行壓縮,前兩者方法http://blog.csdn.NET/mideveloper/article/details/11473627這位哥們講的已經(jīng)很詳細(xì)了,我自己用OC和Swift寫(xiě)了一個(gè)UIImage的分類(lèi),也比較好用.
OC:
+(UIImage *)reduceScaleToWidth:(CGFloat)width andImage:(UIImage *)image{
if (image.size.width <= width) {
return image;
}
CGFloat height = image.size.height * (width/image.size.width);
CGRect rect = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage * returnImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return returnImage;
}
SWIFT
/// 將圖片按指定寬度縮放
///
/// - parameter width: 指定寬度
///
/// - returns: <#return value description#>
func scaleToWidth(width: CGFloat) -> UIImage {
if size.width <= width {
return self
}
// 計(jì)算高度
let height = size.height * (width / size.width)
let rect = CGRect(x: 0, y: 0, width: width, height: height)
// 開(kāi)啟圖形上下文
UIGraphicsBeginImageContext(rect.size)
// 畫(huà)
self.drawInRect(rect)
// 取
let image = UIGraphicsGetImageFromCurrentImageContext()
// 關(guān)閉上下文
UIGraphicsEndImageContext()
return image
}