Swift相簿選擇和拍照功能

weixin_33724059發表於2017-05-05

專案開發中經常會有更改使用者頭像和上傳圖片等場景會用到圖片的選擇。為了方便以後的使用,整合了一個簡單的選擇圖片的功能

這次是用swift 3.0 寫的,主要是建立了一個控制器YMImgPickerVC.swift
檔案程式碼如下

//圖片選擇器

import UIKit

var  width = UIScreen.main.bounds.width
var  heigth = UIScreen.main.bounds.height

class YMImgPickerVC: UIViewController {

    
    var bgView : UIView?
    var cancelBtn : UIButton?
    var photoBtn : UIButton?
    var cameraBtn : UIButton?
    var callbackWithImg : ((_ imgData:Data) -> Void)? = nil //閉包返回圖片資料
    
    
    var  imagePickerCtr : UIImagePickerController!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        initImagePickerCtr()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

        
    }
    

}



//設定介面
extension YMImgPickerVC {

    fileprivate func setupUI(){
        //背景View
        bgView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height - 127, width: UIScreen.main.bounds.width, height: 127))
        bgView?.backgroundColor = UIColor.gray
        guard let bgview1 = bgView else {
            return ;
        }
        view.addSubview(bgview1)
        
        //取消按鈕
        cancelBtn = UIButton(frame: CGRect(x: 0, y: 87, width: UIScreen.main.bounds.width, height: 40))
        cancelBtn?.setTitle("取消", for: .normal)
        cancelBtn?.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        cancelBtn?.setTitleColor(UIColor.black, for: .normal)
        cancelBtn?.tag = 10001
        cancelBtn?.backgroundColor = UIColor.white
        guard let btn = cancelBtn else {
            return ;
        }
        bgView?.addSubview(btn)
        
        
        //相簿選擇按鈕
        photoBtn = UIButton(frame: CGRect(x: 0, y: 41, width: UIScreen.main.bounds.width, height: 40))
        photoBtn?.setTitle("從相簿選擇", for: .normal)
        photoBtn?.setTitleColor(UIColor.black, for: .normal)
        photoBtn?.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        photoBtn?.tag = 10002
        photoBtn?.backgroundColor = UIColor.white
        guard let btn1 = photoBtn else {
            return ;
        }
        bgView?.addSubview(btn1)
        
        
        //照相按鈕
        cameraBtn = UIButton(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        cameraBtn?.setTitle("拍照", for: .normal)
        cameraBtn?.setTitleColor(UIColor.black, for: .normal)
        cameraBtn?.tag = 10003
        cameraBtn?.backgroundColor = UIColor.white
        cameraBtn?.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        guard let btn2 = cameraBtn else {
            return ;
        }
        bgView?.addSubview(btn2)
 
    }
    
    fileprivate func initImagePickerCtr(){
    
        imagePickerCtr = UIImagePickerController()
        imagePickerCtr.delegate = self
        //設定是否可以管理已經存在的圖片或視訊
        imagePickerCtr.allowsEditing = true
        
        
        
    }
    

}




//按鈕帶點選的方法
extension YMImgPickerVC {

    
    @objc fileprivate func btnClick(btn : UIButton){
        switch btn.tag {
           
        case 10001:
            YMlog(message:btn.currentTitle!+"\(btn.tag)")
            self.dismiss(animated: true, completion: {
                
            })
       
            
            
        case 10002:
            //相簿
            YMlog(message:btn.currentTitle!+"\(btn.tag)")
            chooseImg(type: .photoLibrary)
           
            
        case 10003:
             //相機
            YMlog(message:btn.currentTitle!+"\(btn.tag)")
            chooseImg(type: .camera)
        default:
            break 
        }
        
    }
    
    
    
    //相簿選擇或拍照
    func chooseImg(type:UIImagePickerControllerSourceType){
        
        imagePickerCtr.sourceType = type
        if UIImagePickerController.isSourceTypeAvailable(type){
            self.present(imagePickerCtr, animated: true, completion: { 
                
            })
            
        }else{
            YMPrint(message: "沒有許可權")
        }
        
        
    }

}



//MARK: - UIImagePickerControllerDelegate
extension YMImgPickerVC : UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let  img = info[UIImagePickerControllerOriginalImage] as? UIImage
        
        
        
        //壓縮圖片
        //預設壓縮到100KB
        let  imgData = compressImage(image: img ?? UIImage(), maxLength: 1024*100) //  UIImageJPEGRepresentation(img!, 0.5)
        YMPrint(message: imgData)
        picker.dismiss(animated: true, completion: {
            
            guard let data = imgData else {
                return ;
            }
            self.callbackWithImg!(data)
            
        })
        self.dismiss(animated: true) { 
            
        }
    
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true) { 
            
        }
        self.dismiss(animated: true) {
            
        }
    }
    
    

}



//指定壓縮圖片大小
extension YMImgPickerVC {

    
    
    /// 預縮圖片到指定位元組
    ///
    /// - Parameters:
    ///   - image: 需要壓縮的圖片
    ///   - maxLength: 壓縮的大小
    /// - Returns: 返回壓縮的圖片
    fileprivate func compressImage(image : UIImage, maxLength: Int ) -> Data? {
        
        var compress:CGFloat = 0.9
        var data = UIImageJPEGRepresentation(image, compress)
        while (data?.count)! > maxLength && compress > 0.01 {
            compress -= 0.02
            data = UIImageJPEGRepresentation(image, compress)
        }
        return data
    }

}


具體用法:

 let imgPickerVC  = YMImgPickerVC()
            imgPickerVC.modalPresentationStyle = .overCurrentContext //模態檢視的展現形式
            imgPickerVC.view.backgroundColor = UIColor(white: 0.3, alpha: 0.7) //檢視的背景顏色
            imgPickerVC.callbackWithImg = {(imgData:Data) in
                let cell = self.tableView(tableView, cellForRowAt: indexPath)
                cell.imageView?.image = UIImage(data: imgData)
                YMPrint(message: imgData)
                self.headerView.image = UIImage(data: imgData)
                self.tableView?.tableHeaderView = self.headerView
                
                
                
            }

3611162-51ff8e09ce5743c4.PNG
IMG_1715.PNG

git地址:https://github.com/juliankeji/YMTool/tree/master/YMTool

相關文章