位置:首頁 > 手機開發 > iOS基礎教程 > IOS - 攝像頭管理

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