最近做的项目中用到了从本地相册获取图片,所以整理出来分享给大家 YoY
因为我们要用到相册,所以我们要遵循两个代理UIImagePickerControllerDelegate,UINavigationControllerDelegate,因为我用到了手势点击图片,所以又遵循了UIGestureRecognizerDelegate,好啦,我们来看代码
import UIKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate {
var imageView: UIImageView?
var imageUrl: NSURL?
override func viewDidLoad() {
super.viewDidLoad()
//创建一个imageView 将图片设置成圆形
imageView = UIImageView(frame: CGRectMake(100, 100, 80, 80))
imageView?.userInteractionEnabled = true
imageView?.backgroundColor = UIColor.cyanColor()
imageView?.layer.masksToBounds = true
imageView?.layer.cornerRadius = 40.0
view.addSubview(imageView!)
//添加手势
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapGesture(_:)))
tap.delegate = self
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
imageView!.addGestureRecognizer(tap)
}
//点击头像
func tapGesture(tap:UITapGestureRecognizer) {
let aleat = UIAlertController(title: "照片选择", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
weak var weakSelf = self;
let aleartAction = UIAlertAction(title: "相册", style: UIAlertActionStyle.Default) { (_) -> Void in
self.imageVC.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
weakSelf!.presentViewController(self.imageVC, animated: true, completion: nil);
}
let aleartAction_two = UIAlertAction(title: "相机", style: UIAlertActionStyle.Default) { (_) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
{
weakSelf!.imageVC.sourceType = UIImagePickerControllerSourceType.Camera
weakSelf?.presentViewController(weakSelf!.imageVC, animated: true
, completion: nil)
}
}
let aleartAction_cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel) { (_) -> Void in
}
aleat.addAction(aleartAction);
aleat.addAction(aleartAction_two);
aleat.addAction(aleartAction_cancel);
self.presentViewController(aleat, animated: true, completion: nil);
}
//懒加载创建imageVC
private lazy var imageVC:UIImagePickerController = {
let imageVc = UIImagePickerController()
imageVc.delegate = self
return imageVc;
}()
// 选择完成图片后调用的方法
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//获取点击图片的url和image
imageUrl = info["UIImagePickerControllerReferenceURL"] as? NSURL
let image = info["UIImagePickerControllerOriginalImage"] as? UIImage
let imageView = UIImageView()
imageView.image = image
imageView.frame = self.imageView!.frame
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = 40.0
view.addSubview(imageView)
dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
好啦,今天就分享到这里咯,请大家多多指教,( _ )/~~拜拜