首先,添加UINavigationControllerDelegate和UIImagePickerControllerDelegate两项PRotocol.
使用UIImagePickerController,就必须实现UINavigationControllerDelegate这个protocol,因为调用过程中会出现NavigationBar,如果没实现,也不会说运行不了。只是Xcode会直接就给你一个warning.
直接上自己用swift写的一个设置头像的小demo,可直接复制使用。注释清晰明了。
1//2//ViewController.swift3//ImageDemo4//5//Created by fanviwa on 15/4/22.6//Copyright (c) 2015年 fanviwa. All rights reserved.7//89import UIKit1011classViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {1213@IBOutlet weak var imageView: UIImageView!14//初始化图片选择控制器15let imagePickerController: UIImagePickerController =UIImagePickerController()16var isFullScreen: Bool =false1718overridefunc viewDidLoad() {19super.viewDidLoad()20//Do any additional setup after loading the view, typically from a nib.21self.imageView.frame = CGRectMake(100,100,128,128)22}2324overridefunc didReceiveMemoryWarning() {25super.didReceiveMemoryWarning()26//Dispose of any resources that can be recreated.27}2829@IBAction func chooseImage(sender: UIButton) {30//设置代理31self.imagePickerController.delegate=self32//设置是否可以管理已经存在的图片或者视频33self.imagePickerController.allowsEditing =true3435//判断是否支持相机36if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){37let alertController: UIAlertController =UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)38//在ipad上使用表单(ActionSheet)需要设置描点(anchor point)39var popover =alertController.popoverPresentationController40if(popover !=nil){41popover?.sourceView =sender42popover?.sourceRect =sender.bounds43popover?.permittedArrowDirections =UIPopoverArrowDirection.Any44}4546let cameraAction: UIAlertAction = UIAlertAction(title:"拍照换头像", style: .Default) { (action: UIAlertAction!) -> Voidin47//设置类型48self.imagePickerController.sourceType =UIImagePickerControllerSourceType.Camera49self.presentViewController(self.imagePickerController, animated:true, completion: nil)50}51alertController.addAction(cameraAction)5253let photoLibraryAction: UIAlertAction = UIAlertAction(title:"从相册选择换头像", style: .Default) { (action: UIAlertAction!) -> Voidin54//设置类型55self.imagePickerController.sourceType =UIImagePickerControllerSourceType.PhotoLibrary56//改navigationBar背景色57self.imagePickerController.navigationBar.barTintColor = UIColor(red:171/255, green:202/255, blue:41/255, alpha:1.0)58//改navigationBar标题色59self.imagePickerController.navigationBar.titleTextAttributes =[NSForegroundColorAttributeName: UIColor.whiteColor()]60//改navigationBar的button字体色61self.imagePickerController.navigationBar.tintColor =UIColor.whiteColor()62self.presentViewController(self.imagePickerController, animated:true, completion: nil)63}64alertController.addAction(photoLibraryAction)6566let cancelAction: UIAlertAction = UIAlertAction(title:"取消", style: .Cancel, handler: nil)67alertController.addAction(cancelAction)6869presentViewController(alertController, animated:true, completion: nil)7071}else{72let alertController: UIAlertController =UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)73//设置描点(anchor point)74var popover =alertController.popoverPresentationController75if(popover !=nil){76popover?.sourceView =sender77popover?.sourceRect =sender.bounds78popover?.permittedArrowDirections =UIPopoverArrowDirection.Any79}8081let photoLibraryAction: UIAlertAction = UIAlertAction(title:"从相册选择换头像", style: .Default) { (action: UIAlertAction!) -> Voidin82//设置类型83self.imagePickerController.sourceType =UIImagePickerControllerSourceType.PhotoLibrary84//改navigationBar背景色85self.imagePickerController.navigationBar.barTintColor = UIColor(red:171/255, green:202/255, blue:41/255, alpha:1.0)86//改navigationBar标题色87self.imagePickerController.navigationBar.titleTextAttributes =[NSForegroundColorAttributeName: UIColor.whiteColor()]88//改navigationBar的button字体色89self.imagePickerController.navigationBar.tintColor =UIColor.whiteColor()90self.presentViewController(self.imagePickerController, animated:true, completion: nil)91}92alertController.addAction(photoLibraryAction)9394let cancelAction: UIAlertAction = UIAlertAction(title:"取消", style: .Cancel, handler: nil)95alertController.addAction(cancelAction)9697presentViewController(alertController, animated:true, completion: nil)98}99}100101//实现ImagePicker delegate 事件102func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {103picker.dismissViewControllerAnimated(true, completion: nil)104var image: UIImage!105//判断,图片是否允许修改106if(picker.allowsEditing){107//裁剪后图片108image = info[UIImagePickerControllerEditedImage]as!UIImage109}else{110//原始图片111image = 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//保存图片至本地,方法见下文123self.saveImage(image, newSize: CGSize(width:256, height:256), percent:0.5, imageName:"currentImage.png")124let fullPath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents").stringByAppendingPathComponent("currentImage.png")125println("fullPath=\(fullPath)")126let savedImage: UIImage = UIImage(contentsOfFile: fullPath)!127self.isFullScreen =false128self.imageView.image =savedImage129//在这里调用网络通讯方法,上传头像至服务器...130}131//当用户取消时,调用该方法132func imagePickerControllerDidCancel(picker: UIImagePickerController) {133self.dismissViewControllerAnimated(true, completion: nil)134}135136//保存图片至沙盒137func saveImage(currentImage: UIImage, newSize: CGSize, percent: CGFloat, imageName: String){138//压缩图片尺寸139UIGraphicsBeginImageContext(newSize)140currentImage.drawInRect(CGRect(x:0, y:0, width: newSize.width, height: newSize.height))141let newImage: UIImage =UIGraphicsGetImageFromCurrentImageContext()142UIGraphicsEndImageContext()143//高保真压缩图片质量144//UIImageJPEGRepresentation此方法可将图片压缩,但是图片质量基本不变,第二个参数即图片质量参数。145let imageData: NSData =UIImageJPEGRepresentation(newImage, percent)146//获取沙盒目录,这里将图片放在沙盒的documents文件夹中147let fullPath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents").stringByAppendingPathComponent(imageName)148//将图片写入文件149imageData.writeToFile(fullPath, atomically:false)150}151152//实现点击图片预览功能,滑动放大缩小,带动画153overridefunc touchesBegan(touches: Set<NSObject>, withEventevent: UIEvent) {154self.isFullScreen = !self.isFullScreen155156let touch: UITouch = touches.firstas!UITouch157let touchPoint: CGPoint =touch.locationInView(self.view)158let imagePoint: CGPoint =self.imageView.frame.origin159//touchPoint.x ,touchPoint.y 就是触点的坐标160//触点在imageView内,点击imageView时 放大,再次点击时缩小161if(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//设置图片放大动画163UIView.beginAnimations(nil, context: nil)164//动画时间165UIView.setAnimationDuration(1)166167if(isFullScreen) {168//放大尺寸169self.imageView.frame = CGRectMake(0,0,480,320)170}171else{172//缩小尺寸173self.imageView.frame = CGRectMake(100,100,128,128)174}175//commit动画176UIView.commitAnimations()177}178}179}
其次,还有一些检查是否有硬件的方法。
1//判断设备是否有摄像头2UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)3//前面的摄像头是否可用4UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)5//后面的摄像头是否可用6UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Rear)7//相册是否可用8UIImagePickerController.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.
”是正常的,暂无解决办法。
希望对你有帮助!