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
廣告