ios - AVFoundation 相机预览层不工作

标签 ios camera avfoundation

所以,我正在尝试使用 AVFoundation 实现一个相机。我想我做的一切都是对的。这就是我正在做的

  1. 创建 session
  2. 获取视频类型的设备
  3. 遍历设备以获取背面的摄像头
  4. 使用#3 中提到的设备获取设备输入并将其添加到 session 中
  5. 创建类型为 AVCaptureStillImageOutput 的输出
  6. 设置输出设置并将其添加到 session
  7. 从我的 View 2 中获取一个 CALayer(下面将解释我所说的 View 2 的含义)
  8. 创建一个 AVCaptureVideoPreviewLayer 实例
  9. 将其添加到#7 中提到的图层
  10. 开始运行 session

所以我有 2 个观点。上面的是 View 1,下面的是 View 2。 View 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];

我得到的是 View 1(它有一个 .png 图像作为背景。图像有一个洞,以便它下面的 View 、 View 2 可见)和 View 2 是可见的,但我看不到我是什么应该。因为我将 View 2 的背景颜色更改为清晰颜色,所以我看到全黑。我应该看到相机看到的东西。

最佳答案

事实证明,您必须设置 frame、maskToBounds 和 gravity 才能使预览层正常工作。我是这样做的

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];

关于ios - AVFoundation 相机预览层不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334118/

相关文章:

ios - 获取MPNowPlayingInfoCenter的nowPlayingInfo中显示的元数据(锁屏和远程控制)

ios - 如何从顶部裁剪视频?

ios - Chartboost 委托(delegate)错误

android - 拍摄的照片方向在 android 中发生变化

ios - 使用 map 边界和固定 y 位置将相机约束在角色上 - SpriteKit

iphone - 是否有可以通过应用程序控制的 iphone/ipad 相机硬件滤镜?

ios - 从 AVSession 压缩 ios 视频

ios - 通过蓝牙发送信息

iphone - Xcode 4 跳过将应用程序复制到设备/模拟器

objective-c - 用于 Cocoa-touch 的 NSNumberFormatter?