如何子查看相机视图?

我正在制作一个应用程序,让用户看到自己在“镜子”(设备上的前置摄像头)。 我知道使用视图覆盖制作UIImageViewController的多种方式,但是我希望我的应用能够以相反的方式进行创作。 在我的应用程序中,我希望相机视图成为主视图的子视图,不需要快门animation,也不需要捕捉照片或拍摄video,也不需要全屏显示。 有任何想法吗?

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

你想创build一个AVCaptureSession并设置适当的输出和input。 一旦configuration完成,你可以得到一个AVCapturePreviewLayer ,它可以被添加到你在视图控制器中configuration的视图中。 预览图层有许多属性,允许您控制如何显示预览。

 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:来捕获图像。

有关如何构buildAVFoundation的更多信息,以及如何更详细地检查Apple Docs的示例。 苹果的AVCamDemo也把这一切都展现出来了