Swift details UIImagePickerController calls the album camera function, uiimagepicker

Source: Internet
Author: User

Swift details UIImagePickerController calls the album camera function, uiimagepicker

First, add the UINavigationControllerDelegate and UIImagePickerControllerDelegate protocol.
To use UIImagePickerController, you must implement the UINavigationControllerDelegate protocol, because the NavigationBar will appear during the call process. If it is not implemented, it will not be said that it cannot run. Only Xcode will directly give you a warning.

You can directly copy and use a small demo that uses swift to set the Avatar. The annotations are clear and clear.

  

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 // initialize image select controller 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. didReceiveMem OryWarning () 26 // Dispose of any resources that can be recreated. 27} 28 29 @ IBAction func chooseImage (sender: UIButton) {30 // set proxy 31 self. imagePickerController. delegate = self 32 // sets whether to manage existing images or videos 33 self. imagePickerController. allowsEditing = true 34 35 // determine whether the camera supports 36 if (UIImagePickerController. isSourceTypeAvailable (UIImagePickerControllerSourceType. camera) {37 let alertController: UIA LertController = UIAlertController (title: nil, message: nil, preferredStyle: UIAlertControllerStyle. actionSheet) 38 // you need to set anchor point 39 var popover = alertController to use the form (ActionSheet) on the iPad. popoverPresentationController 40 if (popover! = Nil) {41 popover ?. SourceView = sender 42 popover ?. SourceRect = sender. bounds 43 popover ?. PermittedArrowDirections ctions = UIPopoverArrowDirection. Any 44} 45 46 let cameraAction: UIAlertAction = UIAlertAction (title: "photo for Avatar", style:. Default) {(action: UIAlertAction !) -> Void in 47 // set type 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: "select an Avatar from album", style :. default) {(action: UIAlertAction !) -> Void in 54 // set type 55 self. imagePickerController. sourceType = UIImagePickerControllerSourceType. photoLibrary 56 // modify the navigationBar background color 57 self. imagePickerController. navigationBar. barTintColor = UIColor (red: 171/255, green: 202/255, blue: 41/255, alpha: 1.0) 58 // modify the navigationBar title Color 59 self. imagePickerController. navigationBar. titleTextAttributes = [NSForegroundColorAttributeName: UIColor. whiteColor ()] 60 // modify the font color of the button in navigationBar 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: "cancel", 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: complete. actionSheet) 73 // set the anchor point 74 var popover = alertController. popoverPresentationController 75 if (popover! = Nil) {76 popover ?. SourceView = sender 77 popover ?. SourceRect = sender. bounds 78 popover ?. PermittedArrowDirections ctions = UIPopoverArrowDirection. Any 79} 80 81 let photoLibraryAction: UIAlertAction = UIAlertAction (title: "select an Avatar from album", style:. Default) {(action: UIAlertAction !) -> Void in 82 // set the type 83 self. imagePickerController. sourceType = UIImagePickerControllerSourceType. photoLibrary 84 // modify the navigationBar background color 85 self. imagePickerController. navigationBar. barTintColor = UIColor (red: 171/255, green: 202/255, blue: 41/255, alpha: 1.0) 86 // modify the navigationBar title Color 87 self. imagePickerController. navigationBar. titleTextAttributes = [NSForegroundColorAttributeName: UIColor. whiteColor ()] 88 // change the button font color of navigationBar 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: "cancel", style :. cancel, handler: nil) 95 alertController. addAction (cancelAction) 96 97 PresentViewController (alertController, animated: true, completion: nil) 98} 99} 100 101 // implement ImagePicker delegate event 102 func imagePickerController (picker: UIImagePickerController, interval info: [NSObject: any object]) {103 picker. dismissViewControllerAnimated (true, completion: nil) 104 var image: UIImage! 105 // determine whether the image can be modified 106 if (picker. allowsEditing) {107 // After cropping the image 108 image = info [UIImagePickerControllerEditedImage]! UIImage109} else {110 // original image 111 image = info [UIImagePickerControllerOriginalImage]! UIImage112} 113/* info has six values: 114 * UIImagePickerControllerMediaType; // an NSString UTTypeImage) 115 * UIImagePickerControllerOriginalImage; // a UIImage original image 116 * snapshot; // a UIImage cropped image 117 * UIImagePickerControllerCropRect; // an NSValue (CGRect) 118 * UIImagePickerControllerMediaURL; // an NSURL119 * response // an NSURL that references N asset in the AssetsLibrary framework120 * UIImagePickerControllerMediaMetadata // an NSDictionary containing metadata from a captured photo121 */122 // Save the image locally. For details, see section 123 self. saveImage (image, newSize: CGSize (width: 256, height: 256), percent: 0.5, imageName: "currentImage.png") 124 let fullPath: String = NSHomeDirectory (). stringByAppendingPathComponent ("events "). stringByAppendingPathComponent (" CurrentImage.png ") 125 println (" fullPath = \ (fullPath) ") 126 let savedImage: UIImage = UIImage (contentsOfFile: fullPath )! 127 self. isFullScreen = false128 self. imageView. image = savedImage129 // call the network communication method here and upload the Avatar to the server... 130} 131 // call this method 132 func imagePickerControllerDidCancel (picker: UIImagePickerController) {133 self. dismissViewControllerAnimated (true, completion: nil) 134} 135 136 // Save the image to sandbox 137 func saveImage (currentImage: UIImage, newSize: CGSize, percent: CGFloat, imageName: String) {138 // compressed image size: 139 UIGraphicsBeg InImageContext (newSize) 140 currentImage. drawInRect (CGRect (x: 0, y: 0, width: newSize. width, height: newSize. height) 141 let newImage: UIImage = watermark () 142 UIGraphicsEndImageContext () 143 // high fidelity compression image quality 144 // UIImageJPEGRepresentation this method can compress the image, but the image quality remains unchanged, the second parameter is the image quality parameter. 145 let imageData: NSData = UIImageJPEGRepresentation (newImage, percent) 146 // get the sandbox directory. Put the image in the sandbox's documents folder 147 let fullPath: String = NSHomeDirectory (). stringByAppendingPathComponent ("events "). stringByAppendingPathComponent (imageName) 148 // write the image to the file 149 imageData. writeToFile (fullPath, atomically: false) 150} 151 152 // Click image preview, slide to zoom in and zoom out, with animation 153 override func touchesBegan (touches: Set <NSObject>, wit HEvent event: UIEvent) {154 self. isFullScreen =! Self. isFullScreen155 156 let touch: UITouch = touches. first! UITouch157 let touchPoint: CGPoint = touch. locationInView (self. view) 158 let imagePoint: CGPoint = self. imageView. frame. origin159 // touchPoint. x, touchPoint. y is the contact coordinate 160 // the contact is in the imageView. When you click imageView, the contact is enlarged. When you click again, the contact is reduced by 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 // sets the image zoomed animation 163 UIView. beginAnimations (nil, context: nil) 164 // animation time 165 UIView. setAnimationDuration (1) 166 167 if (isFullScreen) {168 // zoom in size 169 self. imageView. frame = CGRectMake (0, 0,480,320) 170} 171 else {172 // reduce the size by 173 self. imageView. frame = CGRectMake (100,100,128,128) 174} 175 // commit animation 176 UIView. commitAnimations () 177} 178} 179}

Second, there are some methods to check whether there is hardware.

1 // determine whether the device has a camera 2 UIImagePickerController. isSourceTypeAvailable (UIImagePickerControllerSourceType. camera) 3 // whether the front Camera is available 4 UIImagePickerController. isCameraDeviceAvailable (UIImagePickerControllerCameraDevice. front) 5 // whether the backend camera is available 6 UIImagePickerController. isCameraDeviceAvailable (UIImagePickerControllerCameraDevice. rear) 7 // whether the album is available 8 UIImagePickerController. isSourceTypeAvailable (UIImagePickerControllerSourceType. photoLibrary)

Of course, if you want to modify the photo album page to Chinese, add the "Localized resources can be mixed" attribute in the Info. plist configuration file and set it to YES.

Note: After iOS8.0, the system prompts"

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.

"Is normal and there is no solution.

Hope to help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.