相機(jī)是移動(dòng)設(shè)備的共同特點(diǎn)之一,我們能夠使用相機(jī)拍攝圖片,并在應(yīng)用程序里調(diào)用它,而且相機(jī)的使用很簡(jiǎn)單。
1、創(chuàng)建一個(gè)簡(jiǎn)單的View based application
2、在ViewController.xib中添加一個(gè)button (按鈕),并為該按鈕創(chuàng)建IBAction
3、添加一個(gè) image view (圖像視圖),并創(chuàng)建一個(gè)名為imageView的IBOutlet
4、ViewController.h文件代碼如下所示:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIImagePickerControllerDelegate> { UIImagePickerController *imagePicker; IBOutlet UIImageView *imageView; } - (IBAction)showCamera:(id)sender; @end
5、修改ViewController.m,如下所示:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)showCamera:(id)sender { imagePicker.allowsEditing = YES; if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; } else{ imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; } [self presentModalViewController:imagePicker animated:YES]; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; if (image == nil) { image = [info objectForKey:UIImagePickerControllerOriginalImage]; } imageView.image = image; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [self dismissModalViewControllerAnimated:YES]; } @end
運(yùn)行該應(yīng)用程序并單擊顯示相機(jī)按鈕時(shí),我們就會(huì)獲得下面的輸出
只要拍照之后,就可以通過移動(dòng)和縮放對(duì)圖片進(jìn)行編輯,如下所示。
更多建議: