IOS - 攝像頭管理


介紹

攝像頭是移動裝置的共同特點之一。這是普遍的,我們用相機拍照,並用它在我們的應用程式也很簡單。

 

涉及的步驟

1. 建立一個簡單的 View based application

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