AVFoundation相机预览图层不起作用

所以,我试图用AVFoundation实现一个摄像头。 我想我做的一切都是正确的。 这是我正在做的

  1. 创build会话
  2. 获取videotypes的设备
  3. 通过设备循环让相机在后面
  4. 使用#3中提到的设备获取设备input并将其添加到会话中
  5. 创build一个AVCaptureStillImageOutputtypes的输出
  6. 设置输出设置并将其添加到会话中
  7. 从我的观点2得到一个CALayer(下面将解释我的意思是视图2)
  8. 创build一个AVCaptureVideoPreviewLayer的实例
  9. 将它添加到#7中提到的层
  10. 开始运行会话

所以我有两个意见一个在另一个。 最上面的是视图1,下面的是视图2.视图1应该提供自定义的摄像头控件。

这里是代码:

 self.session = [[AVCaptureSession alloc]init]; [self.session setSessionPreset:AVCaptureSessionPresetHigh]; NSArray *devices = [[NSArray alloc]init]; devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice *device in devices){ if([device position] == AVCaptureDevicePositionBack){ self.device = device; break; } } NSError *error; self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:&error]; if([self.session canAddInput:self.input]){ [self.session addInput:self.input]; } self.stillImageOutput = [[AVCaptureStillImageOutput alloc]init]; NSDictionary *outputSettings = @{AVVideoCodecKey : AVVideoCodecJPEG}; [self.stillImageOutput setOutputSettings:outputSettings]; [self.session addOutput:self.stillImageOutput]; CALayer *cameraLayer = self.cameraView.layer; self.cameraView.backgroundColor = [UIColor clearColor]; AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session]; [cameraLayer addSublayer:preview]; [self.session startRunning]; 

我得到的是视图1(它有一个.png图像作为背景,图像有一个洞,以便它下面的视图,视图2可以看到),视图2是可见的,但我没有看到我应该。 因为我改变了视图2的背景色来清除颜色,所以我看到全部是黑色的。 我应该看看相机看到什么。

原来,你必须设置框架,maskToBounds和重力为您的预览图层正常工作。 我就是这么做的

 CALayer *cameraLayer = self.cameraView.layer; self.cameraView.backgroundColor = [UIColor clearColor]; [cameraLayer setMasksToBounds:YES]; AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session]; [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill]; [preview setFrame:[cameraLayer bounds]]; [cameraLayer addSublayer:preview];