iOS - 相机管理


相机是移动设备的常见功能之一。我们可以用相机拍照并在我们的应用程序中使用它,而且也很简单。

相机管理 - 涉及的步骤

步骤 1 - 创建一个简单的基于视图的应用程序

步骤 2 -在ViewController.xib中添加一个按钮并为该按钮创建 IBAction。

步骤 3 - 添加图像视图并创建 IBOutlet,将其命名为 imageView。

步骤 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

输出

当我们运行应用程序并单击“显示相机”按钮时,我们将得到以下输出 -

iOS教程

拍照后,我们可以编辑图片,即移动和缩放,如下所示 -

iOS教程