開發中,通常需要用到使用選取多張圖片的功能,但是高清大圖很吃內存,我想到的處理方案就是拿到高清大圖的時候,重新繪制一張小的圖片使用.至於清晰度尚可,至少我是分辨不出多大區別.
基本思路就是先固定寬,然后根據寬高比重新繪制一張新圖片使用,大致代碼如下:
為UIImage寫一個extention,方便調用
import UIKit extension UIImage{ //根據傳入的寬度生成一張按照寬高比壓縮的新圖片 func imageWithScale(width:CGFloat) -> UIImage{ //1.根據 寬度 計算高度 let height = width * size.height / size.width //2.按照寬高比繪制一張新的圖片 let currentSize = CGSize.init(width: width, height: height) UIGraphicsBeginImageContext(currentSize) //開始繪制 draw(in: CGRect.init(origin: CGPoint.zero, size: currentSize)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //結束上下文 return newImage! } }
控制器代碼:
import UIKit
var identifier = "cell"
private var imgAry = [UIImage]()
class ViewController: UIViewController{
@IBOutlet weak var btn: UIButton!
@IBOutlet weak var colectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
colectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: identifier)
colectionView.delegate = self
colectionView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//選擇 按鈕點擊事件 彈出相冊
@IBAction func btnAction(_ sender: UIButton) {
let vc = UIImagePickerController()
vc.delegate = self
present(vc, animated: true, completion: nil)
}
}
extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return imgAry.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = colectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
let imgView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
if(imgAry.count > 0){
imgView.image = imgAry[indexPath.item]
}
cell.addSubview(imgView)
return cell
}
//選擇圖片
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
let image = info["UIImagePickerControllerOriginalImage"] as! UIImage //選擇的圖片
let newImage = image.imageWithScale(width: 500) //按照寬為500的寬高比給圖片重新繪制新的圖片
imgAry.append(newImage)
colectionView.reloadData()
picker.dismiss(animated: true, completion: nil)
}
}
占用內存情況如下:
未使用照片:25.7 MB
使用未壓縮的照片: 333.1MB
使用壓縮之后的照片:53.9MB
demo源碼:https://github.com/pheromone/swift-imagePicker-memory