jab
jab

Reputation: 5823

Setting a background image/view to live camera view?

Is it possible to set a background for a particular view controller to show a live camera view? If so, could one lead me in the right direction to make this possible?

Upvotes: 5

Views: 6245

Answers (3)

sash
sash

Reputation: 8747

Import:

#import <AVFoundation/AVFoundation.h>

To add camera view to a controller's view add this code in the viewDidLoad:

AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetHigh;

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
[session addInput:input];

AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
newCaptureVideoPreviewLayer.frame = self.view.bounds;

[self.view.layer addSublayer:newCaptureVideoPreviewLayer];

[session startRunning];

Upvotes: 8

Andrei G.
Andrei G.

Reputation: 1740

Yes, definitely possible. You can embed live camera feed in UIView, which you can place anywhere you like.

Start by reading here: AVFoundation Reference - this is your framework

Particular class that you are looking for is AVCaptureVideoPreviewLayer

Which works in unison with AVCaptureSession

And this is an example project that covers everything you need: AVCam

Upvotes: 9

danh
danh

Reputation: 62686

I think your best bet is to grab and understand this apple sample code, called AVCam. You'll see in the code how to create an AVCaptureVideoPreviewLayer. You'll insert this as a sublayer of a UIView that you'll use as your "background".

Once you've got that working, that UIView will be just like any other part of your view hierarchy. You can treat it like a background UIImageView (albeit, one that consumes a lot more batter power).

Upvotes: 3

Related Questions