如何子视图相机视图



我正在制作一个应用程序,让用户在"镜子"(设备上的前置摄像头)中看到自己。 我知道有多种方法可以制作具有视图覆盖的 UIImageViewController,但我希望我的应用程序具有相反的方式。 在我的应用程序中,我希望相机视图是主视图的子视图,没有快门动画或捕获照片或拍摄视频的功能,并且没有全屏。 有什么想法吗?

实现此目的的最佳方法是不使用内置的 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 文档。苹果的AVCamDemo也列出了所有这些。

最新更新