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 Tutorial

一旦拍下照片,便可以编辑照片,即移动和缩放,如下所示 −

iOS Tutorial
广告