Swift詳解UIImagePickerController調用相簿相機功能,uiimagepicker
首先,添加UINavigationControllerDelegate和UIImagePickerControllerDelegate兩項protocol.
使用UIImagePickerController,就必須實現UINavigationControllerDelegate這個protocol,因為調用過程中會出現NavigationBar,如果沒實現,也不會說運行不了。只是Xcode會直接就給你一個warning.
直接上自己用swift寫的一個設定頭像的小demo,可直接複製使用。注釋清晰明了。
1 // 2 // ViewController.swift 3 // ImageDemo 4 // 5 // Created by fanviwa on 15/4/22. 6 // Copyright (c) 2015年 fanviwa. All rights reserved. 7 // 8 9 import UIKit 10 11 class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 12 13 @IBOutlet weak var imageView: UIImageView! 14 // 初始化圖片選擇控制器 15 let imagePickerController: UIImagePickerController = UIImagePickerController() 16 var isFullScreen: Bool = false 17 18 override func viewDidLoad() { 19 super.viewDidLoad() 20 // Do any additional setup after loading the view, typically from a nib. 21 self.imageView.frame = CGRectMake(100, 100, 128, 128) 22 } 23 24 override func didReceiveMemoryWarning() { 25 super.didReceiveMemoryWarning() 26 // Dispose of any resources that can be recreated. 27 } 28 29 @IBAction func chooseImage(sender: UIButton) { 30 // 設定代理 31 self.imagePickerController.delegate = self 32 // 設定是否可以管理已經存在的圖片或者視頻 33 self.imagePickerController.allowsEditing = true 34 35 // 判斷是否支援相機 36 if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){ 37 let alertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) 38 //在iPad上使用表單(ActionSheet)需要設定描點(anchor point) 39 var popover = alertController.popoverPresentationController 40 if (popover != nil){ 41 popover?.sourceView = sender 42 popover?.sourceRect = sender.bounds 43 popover?.permittedArrowDirections = UIPopoverArrowDirection.Any 44 } 45 46 let cameraAction: UIAlertAction = UIAlertAction(title: "拍照換頭像", style: .Default) { (action: UIAlertAction!) -> Void in 47 // 設定類型 48 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.Camera 49 self.presentViewController(self.imagePickerController, animated: true, completion: nil) 50 } 51 alertController.addAction(cameraAction) 52 53 let photoLibraryAction: UIAlertAction = UIAlertAction(title: "從相簿選擇換頭像", style: .Default) { (action: UIAlertAction!) -> Void in 54 // 設定類型 55 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary 56 //改navigationBar背景色 57 self.imagePickerController.navigationBar.barTintColor = UIColor(red: 171/255, green: 202/255, blue: 41/255, alpha: 1.0) 58 //改navigationBar標題色 59 self.imagePickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] 60 //改navigationBar的button字型色 61 self.imagePickerController.navigationBar.tintColor = UIColor.whiteColor() 62 self.presentViewController(self.imagePickerController, animated: true, completion: nil) 63 } 64 alertController.addAction(photoLibraryAction) 65 66 let cancelAction: UIAlertAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil) 67 alertController.addAction(cancelAction) 68 69 presentViewController(alertController, animated: true, completion: nil) 70 71 }else{ 72 let alertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) 73 //設定描點(anchor point) 74 var popover = alertController.popoverPresentationController 75 if (popover != nil){ 76 popover?.sourceView = sender 77 popover?.sourceRect = sender.bounds 78 popover?.permittedArrowDirections = UIPopoverArrowDirection.Any 79 } 80 81 let photoLibraryAction: UIAlertAction = UIAlertAction(title: "從相簿選擇換頭像", style: .Default) { (action: UIAlertAction!) -> Void in 82 // 設定類型 83 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary 84 //改navigationBar背景色 85 self.imagePickerController.navigationBar.barTintColor = UIColor(red: 171/255, green: 202/255, blue: 41/255, alpha: 1.0) 86 //改navigationBar標題色 87 self.imagePickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] 88 //改navigationBar的button字型色 89 self.imagePickerController.navigationBar.tintColor = UIColor.whiteColor() 90 self.presentViewController(self.imagePickerController, animated: true, completion: nil) 91 } 92 alertController.addAction(photoLibraryAction) 93 94 let cancelAction: UIAlertAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil) 95 alertController.addAction(cancelAction) 96 97 presentViewController(alertController, animated: true, completion: nil) 98 } 99 }100 101 //實現ImagePicker delegate 事件102 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {103 picker.dismissViewControllerAnimated(true, completion: nil)104 var image: UIImage!105 // 判斷,圖片是否允許修改106 if(picker.allowsEditing){107 //裁剪後圖片108 image = info[UIImagePickerControllerEditedImage] as! UIImage109 }else{110 //原始圖片111 image = info[UIImagePickerControllerOriginalImage] as! UIImage112 }113 /* 此處info 有六個值114 * UIImagePickerControllerMediaType; // an NSString UTTypeImage)115 * UIImagePickerControllerOriginalImage; // a UIImage 原始圖片116 * UIImagePickerControllerEditedImage; // a UIImage 裁剪後圖片117 * UIImagePickerControllerCropRect; // an NSValue (CGRect)118 * UIImagePickerControllerMediaURL; // an NSURL119 * UIImagePickerControllerReferenceURL // an NSURL that references an asset in the AssetsLibrary framework120 * UIImagePickerControllerMediaMetadata // an NSDictionary containing metadata from a captured photo121 */122 // 儲存圖片至本地,方法見下文123 self.saveImage(image, newSize: CGSize(width: 256, height: 256), percent: 0.5, imageName: "currentImage.png")124 let fullPath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents").stringByAppendingPathComponent("currentImage.png")125 println("fullPath=\(fullPath)")126 let savedImage: UIImage = UIImage(contentsOfFile: fullPath)!127 self.isFullScreen = false128 self.imageView.image = savedImage129 //在這裡調用網路通訊方法,上傳頭像至伺服器...130 }131 // 當使用者取消時,調用該方法132 func imagePickerControllerDidCancel(picker: UIImagePickerController) {133 self.dismissViewControllerAnimated(true, completion: nil)134 }135 136 //儲存圖片至沙箱137 func saveImage(currentImage: UIImage, newSize: CGSize, percent: CGFloat, imageName: String){138 //壓縮圖片尺寸139 UIGraphicsBeginImageContext(newSize)140 currentImage.drawInRect(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))141 let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()142 UIGraphicsEndImageContext()143 //高保真壓縮圖片品質144 //UIImageJPEGRepresentation此方法可將圖片壓縮,但是圖片品質基本不變,第二個參數即圖片品質參數。145 let imageData: NSData = UIImageJPEGRepresentation(newImage, percent)146 // 擷取沙箱目錄,這裡將圖片放在沙箱的documents檔案夾中147 let fullPath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents").stringByAppendingPathComponent(imageName)148 // 將圖片寫入檔案149 imageData.writeToFile(fullPath, atomically: false)150 }151 152 //實現點擊圖片預覽功能,滑動放大縮小,帶動畫153 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {154 self.isFullScreen = !self.isFullScreen155 156 let touch: UITouch = touches.first as! UITouch157 let touchPoint: CGPoint = touch.locationInView(self.view)158 let imagePoint: CGPoint = self.imageView.frame.origin159 //touchPoint.x ,touchPoint.y 就是觸點的座標160 // 觸點在imageView內,點擊imageView時 放大,再次點擊時縮小161 if(imagePoint.x <= touchPoint.x && imagePoint.x + self.imageView.frame.size.width >= touchPoint.x && imagePoint.y <= touchPoint.y && imagePoint.y+self.imageView.frame.size.height >= touchPoint.y){162 // 設定圖片放大動畫163 UIView.beginAnimations(nil, context: nil)164 // 動畫時間165 UIView.setAnimationDuration(1)166 167 if (isFullScreen) {168 // 放大尺寸169 self.imageView.frame = CGRectMake(0, 0, 480, 320)170 }171 else {172 // 縮小尺寸173 self.imageView.frame = CGRectMake(100, 100, 128, 128)174 }175 // commit動畫176 UIView.commitAnimations()177 }178 }179 }
其次,還有一些檢查是否有硬體的方法。
1 // 判斷裝置是否有網路攝影機2 UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)3 // 前面的網路攝影機是否可用4 UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)5 // 後面的網路攝影機是否可用6 UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Rear)7 // 相簿是否可用8 UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
當然,想要修改相簿頁面為中文還的在Info.plist設定檔中添加"Localized resources can be mixed"屬性並設定為YES。
注意:iOS8.0後提示“
Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.
”是正常的,暫無解決辦法。
希望對你有協助!