iOS - 相机管理

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


相机管理 - 涉及的步骤

步骤 1 − 创建一个简单的 View based application 基于视图的应用程序。

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

步骤 3 − 添加 image view 图像视图并创建 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

输出

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

iOS 教程

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

iOS 教程