码迷,mamicode.com
首页 > 编程语言 > 详细

Swift详解UIImagePickerController调用相册相机功能

时间:2015-04-22 13:09:44      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

  首先,添加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! UIImage
109         }else{
110             //原始图片
111             image = info[UIImagePickerControllerOriginalImage] as! UIImage
112         }
113         /* 此处info 有六个值
114         * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
115         * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
116         * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
117         * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
118         * UIImagePickerControllerMediaURL;       // an NSURL
119         * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
120         * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
121         */
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 = false
128         self.imageView.image = savedImage
129         //在这里调用网络通讯方法,上传头像至服务器...
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.isFullScreen
155         
156         let touch: UITouch = touches.first as! UITouch
157         let touchPoint: CGPoint  = touch.locationInView(self.view)
158         let imagePoint: CGPoint = self.imageView.frame.origin
159         //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.

”是正常的,暂无解决办法。

技术分享

希望对你有帮助!

Swift详解UIImagePickerController调用相册相机功能

标签:

原文地址:http://www.cnblogs.com/fanviwa/p/4446760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!