SubView にカメラの映像を映す方法のメモです。

(iOS 5で試しています。 )

注意:

 カメラを使うので、シミュレーターだと動かないです。

カメラの映像をアプリの画面に組み込みたいと思い、

AVCapture Frameworkを使ってみました。

利用する場合、

#import <AVFoundation/AVFoundation.h>

が必要になります。

使ったクラス一覧と簡単な説明

・AVCaptureSession : カメラと画面の繋ぎ

・AVCaptureVideoPreviewLayer:画面表示用レイヤー

・AVCaptureDevice:入力装置

・AVCaptureDeviceInput:カメラからの映像

出力までの概要はこんな感じ

 Layer < — 出力 — Session <– 入力 — DeviceInput

サンプルコード

#import “ViewController.h”

#import <AVFoundation/AVFoundation.h>

@implementation ViewController

– (void)viewDidLoad

{

    [superviewDidLoad];

    

    UIView *videoPreview = [[UIView alloc] initWithFrame:CGRectMake(50, 50 , 200, 200)];

    

    [videoPreview.layer addSublayer:[self videoLayer:videoPreview.bounds]];

    

    [self.view addSubview:videoPreview];

    

}

– (CALayer*)videoLayer:(CGRect)frame

{

    AVCaptureSession *session = [[AVCaptureSessionalloc] init];

    

    AVCaptureVideoPreviewLayer *videoLayer = [[AVCaptureVideoPreviewLayeralloc] initWithSession:session];

    videoLayer.frame = frame;

    

    AVCaptureDevice *captureDevice = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

    

    NSError *error = nil;

    AVCaptureDeviceInput *captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

    if (!captureDeviceInput) {

        NSLog(@”ERROR: %@”, error);

    }

    [session addInput:captureDeviceInput];

    

    [session startRunning];

    

    return videoLayer;

}

@end