• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

swift2选择头像图片

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

一句话选择单个头像图片

新建ImagePickerViewController类:

/* let imagePicker = ImagePickerViewController()

imagePicker.delegate = self

self.presentViewController(imagePicker, animated: false, completion: nil)

*/

实现类代理方法

//MARK: -ImagePickerViewDelegate

extension FourViewController:ImagePickerViewDelegate{

func getImage(image: UIImage) {

headView?.headImage?.image = image

}

}

ImagePickerViewController类中实现代码

import UIKit

import AVFoundation

import MobileCoreServices

protocol ImagePickerViewDelegate {

    func getImage(image:UIImage)

}

 

class ImagePickerViewController: UIViewController,UIActionSheetDelegate {

    

    var delegate:ImagePickerViewDelegate?

    var alertController:UIAlertController?

    var pickCtr:UIImagePickerController?

    

    

    init(){

        super.init(nibName: nil, bundle: nil)

        self.modalPresentationStyle = .OverFullScreen

        self.view.backgroundColor = UIColor.clearColor()

        pickCtr = UIImagePickerController()

        pickCtr!.delegate = self;

        pickCtr!.allowsEditing = true;

        

    }

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    override func viewDidAppear(animated: Bool) {

        super.viewDidAppear(animated)

        if (alertController == nil) {

            alertController = UIAlertController(title: "选择文件源", message: nil, preferredStyle: .ActionSheet)

            

            alertController?.addAction(UIAlertAction(title: "打开相机", style: .Default, handler: { (action) in

                self.takePhoto()

            }))

            

            alertController?.addAction(UIAlertAction(title: "打开相册", style: .Default, handler: { (action) in

                self.localPhoto()

                

            }))

            

            alertController?.addAction(UIAlertAction(title: "取消", style: .Default, handler: { (action) in

                self.dismissViewControllerAnimated(false, completion: nil)

            }))

            self.presentViewController(alertController!, animated: true, completion: nil)

            

        }

    }

    

    /// 打开相册

    func localPhoto(){

        if (self.isPhotoLibraryAvailable()){

            pickCtr?.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

            self.presentViewController(pickCtr!, animated: true, completion: nil)

        }else{

            let alert = UIAlertController(title: nil, message: "相册不可用", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (action) in

                self.dismissViewControllerAnimated(false, completion: nil)

            }))

            self.presentViewController(alert, animated: true, completion: nil)

        }

    }

    /// 打开相机takePhoto

    func takePhoto(){

        let mediaType = AVMediaTypeVideo

        let authStatus = AVCaptureDevice.authorizationStatusForMediaType(mediaType)

        let you = self.isCameraAvailable()==true

        let my = self.doesCameraSupportTakingPhotos()==true

        pprintLog("you:\(you)")

        pprintLog("my:\(my)")

        pprintLog("myandyou:\(my&&you)")

        

        if(authStatus == AVAuthorizationStatus.Restricted || authStatus == AVAuthorizationStatus.Denied){

            let alert = UIAlertController(title: nil, message: "相机不可用,请到系统设置里更改", preferredStyle: UIAlertControllerStyle.Alert)

            

            alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (action) in

                self.dismissViewControllerAnimated(false, completion: nil)

            }))

            self.presentViewController(alert, animated: true, completion: nil)

            

        }else if(self.isCameraAvailable()==true && self.doesCameraSupportTakingPhotos()==true){

            pickCtr!.sourceType = UIImagePickerControllerSourceType.Camera

            self.presentViewController(pickCtr!, animated: true, completion: nil)

        }else{

            let alert = UIAlertController(title: nil, message: "相机不可用", preferredStyle: UIAlertControllerStyle.Alert)

            

            alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: { (action) in

                self.dismissViewControllerAnimated(false, completion: nil)

            }))

            self.presentViewController(alert, animated: true, completion: nil)

        }

        

    }

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        

    }

}

 

//MARK: - UIImagePickerControllerDelegate

extension ImagePickerViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    //取消

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {

        pickCtr?.dismissViewControllerAnimated(true, completion: {

            self.dismissViewControllerAnimated(false, completion: nil)

        })

    }

    // 得到图片

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        let type:String = info[UIImagePickerControllerMediaType] as! String

        

        if (type == kUTTypeImage as String){

            let img:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage

            //对拍照后的照片进行处理

            let image1 = self.fixOrientationIm(img)

            //防止图片翻滚

            let image2 = self.fixOrientationIm(image1)

            //改变图片的size

            let image3 = self.image(image2, targetSize: CGSizeMake(110, 80))

            pickCtr?.dismissViewControllerAnimated(true, completion: {

                self.dismissViewControllerAnimated(false, completion: {

                    self.delegate?.getImage(image3)

                })

            })

        }

    }

    

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        

    }

    

    

    

}

/// 判断手机是否支持。。相机....

extension ImagePickerViewController{

    /// 判断设备是否有摄像头

    func isCameraAvailable()->Bool{

        return UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)

    }

    /// 后面的摄像头是否可用

    func isRearCameraAvailable()->Bool{

        return UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Rear)

    }

    /// 前面的摄像头是否可用

    func isFrontCameraAvailable()->Bool{

        return UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)

    }

    /// 相册是否可用

    func isPhotoLibraryAvailable()->Bool{

        return UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)

    }

    /// 相机是否可以取到图片

    func doesCameraSupportTakingPhotos()->Bool{

        return self.cameraSupportsMedia( kUTTypeImage as String, paramSourceType: UIImagePickerControllerSourceType.Camera)

    }

    /// 相机是否可以取到视频

    func doesCameraSupportTakingVideos()->Bool{

        return self.cameraSupportsMedia( kUTTypeMovie as String, paramSourceType: UIImagePickerControllerSourceType.Camera)

    }

    /// 相册是否可以取到视频

    func canUserPickVideosFromPhotoLibrary()->Bool{

        return self.cameraSupportsMedia(kUTTypeMovie as String, paramSourceType: UIImagePickerControllerSourceType.PhotoLibrary)

    }

    /// 相册是否可以取到图片

    func canUserPickPhotosFromPhotoLibrary()->Bool{

        return self.cameraSupportsMedia(kUTTypeImage as String, paramSourceType: UIImagePickerControllerSourceType.PhotoLibrary)

    }

    

    

    func cameraSupportsMedia(paramMediaType:String,paramSourceType:UIImagePickerControllerSourceType)->Bool{

        var result = false

        if paramMediaType.characters.count==0{

            

            return false

        }

        

        let availableMediaTypes:NSArray? = UIImagePickerController.availableMediaTypesForSourceType(paramSourceType)

        

        if availableMediaTypes != nil{

        availableMediaTypes!.enumerateObjectsUsingBlock { (obj, idx,stop) in

            

            let mediaType:String = obj as! String

            

            if mediaType == paramMediaType{

                result = true

                //        stop = true;

            }

        }

        }

        return result;

    }

}

 

 

 

//MARK: - 图片方法

extension ImagePickerViewController{

    //MARK:- 相机照片处理

    func fixOrientationIm(aImage:UIImage) -> UIImage{

        // No-op if the orientation is already correct

        if (aImage.imageOrientation == UIImageOrientation.Up){

            return aImage

        }

        // We need to calculate the proper transformation to make the image upright.

        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.

        var transform  = CGAffineTransformIdentity

        

        switch (aImage.imageOrientation) {

        case UIImageOrientation.Down:

            break

        case UIImageOrientation.DownMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);

            transform = CGAffineTransformRotate(transform, CGFloat(M_PI));

            break

        case UIImageOrientation.Left:

            break

        case UIImageOrientation.LeftMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

            transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));

            break

        case UIImageOrientation.Right:

            break

        case UIImageOrientation.RightMirrored:

            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);

            transform = CGAffineTransformRotate(transform, -CGFloat(M_PI_2));

            break

        default:

            break

        }

        

        switch (aImage.imageOrientation) {

        case UIImageOrientation.UpMirrored:

            break

        case UIImageOrientation.DownMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);

            transform = CGAffineTransformScale(transform, -1, 1);

            break

        case UIImageOrientation.LeftMirrored:

            break

        case UIImageOrientation.RightMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);

            transform = CGAffineTransformScale(transform, -1, 1);

            break

        default:

            break

        }

        

        // Now we draw the underlying CGImage into a new context, applying the transform

        // calculated above.

        

        let ctx:CGContextRef = CGBitmapContextCreate(nil, Int(aImage.size.width), Int(aImage.size.height), CGImageGetBitsPerComponent(aImage.CGImage!), 0, CGImageGetColorSpace(aImage.CGImage!)!, CGImageGetBitmapInfo(aImage.CGImage!).rawValue)!

        

        CGContextConcatCTM(ctx, transform);

        

        switch (aImage.imageOrientation) {

        case UIImageOrientation.Left:

            break

        case UIImageOrientation.LeftMirrored:

            break

        case UIImageOrientation.Right:

            break

        case UIImageOrientation.RightMirrored:

            // Grr...

            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage!);

            break

            

        default:

            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage!);

            break

        }

        

        // And now we just create a new UIImage from the drawing context

        let cgimg = CGBitmapContextCreateImage(ctx)

        let img = UIImage(CGImage: cgimg!)

        //        CGContextRelease(ctx)

        //        CGImageRelease(cgimg)

        return img;

        

    }

    /// 裁剪图片

    func image(image:UIImage,targetSize:CGSize)-> UIImage{

        UIGraphicsBeginImageContext(targetSize)

        image.drawInRect(CGRectMake(0, 0, targetSize.width, targetSize.height))

        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return newImage!

    }

    

    ///得到图片

    func getImageWithName(iName:String)->UIImage{

        let cloudIcon = UIImage(contentsOfFile: self.cachedPicPath(iName))

        return cloudIcon!

    }

    /// 存储图片

    func saveImage(image:UIImage,name:String){

        UIImagePNGRepresentation(image)?.writeToFile(name, atomically: true)

    }

    /// 获取图片路径

    func cachedPicPath(imageN:String)->String{

        let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask.UserDomainMask, true)

        let documentsPath:NSString = paths.first! as NSString

        let imageName = imageN+".png"

        let path = documentsPath.stringByAppendingPathComponent(imageName)

        return path

    }

    

}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift中的反射发布时间:2022-07-13
下一篇:
Swift-获取、改变按钮的标题文本(UIButton点击切换title)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap