手機中經(jīng)常會遇到一些非常大的圖片,當把它們導入到我們的緩存時有時會造成程序的閃退,即超過了125mb,此時我們有三種方法對圖片進行壓縮,前兩者方法http://blog.csdn.NET/mideveloper/article/details/11473627這位哥們講的已經(jīng)很詳細了,我自己用OC和Swift寫了一個UIImage的分類,也比較好用.
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
}
// 計算高度
let height = size.height * (width / size.width)
let rect = CGRect(x: 0, y: 0, width: width, height: height)
// 開啟圖形上下文
UIGraphicsBeginImageContext(rect.size)
// 畫
self.drawInRect(rect)
// 取
let image = UIGraphicsGetImageFromCurrentImageContext()
// 關閉上下文
UIGraphicsEndImageContext()
return image
}