0

我正在制作一个应用程序,让用户在“镜子”(设备上的前置摄像头)中看到自己。我知道制作带有视图叠加层的 UIImageViewController 的多种方法,但我希望我的应用程序采用相反的方式。在我的应用程序中,我希望相机视图成为主视图的子视图,没有快门动画或捕捉照片或拍摄视频的能力,也没有全屏显示。有任何想法吗?

4

1 回答 1

15

最好的方法是不使用内置的 UIImagePickerController,而是使用AVFoundation类。

您想要创建AVCaptureSession并设置适当的输出和输入。配置完成后,您可以将AVCapturePreviewLayer其添加到您在视图控制器中配置的视图中。预览图层具有许多属性,可让您控制预览的显示方式。

AVCaptureSession *session = [[AVCaptureSession alloc] init];
AVCaptureOutput *output = [[AVCaptureStillImageOutput alloc] init];
[session addOutput:output];

//Setup camera input
NSArray *possibleDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//You could check for front or back camera here, but for simplicity just grab the first device
AVCaptureDevice *device = [possibleDevices objectAtIndex:0];
NSError *error = nil;
// create an input and add it to the session
AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; //Handle errors

//set the session preset 
session.sessionPreset = AVCaptureSessionPresetMedium; //Or other preset supported by the input device   
[session addInput:input];

AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
//Set the preview layer frame
previewLayer.frame = self.cameraView.bounds;
//Now you can add this layer to a view of your view controller
[self.cameraView.layer addSublayer:previewLayer]
[session startRunning];

然后,您可以使用captureStillImageAsynchronouslyFromConnection:completionHandler:输出设备的 来捕获图像。

有关如何构建 AVFoundation 的更多信息以及如何执行此操作的示例,请查看Apple Docs。Apple 的AVCamDemo 也列出了所有这些

于 2012-06-27T18:03:06.113 回答