所以,我正在尝试使用AVFoundation实现相机。我想我做的一切都是正确的。这就是我正在做的事情
AVCaptureStillImageOutput
AVCaptureVideoPreviewLayer
所以我有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图像作为背景。图像有一个洞,因此它下面的视图,视图2可见)和视图2可见但是我看不到我是什么应该。因为我将视图2的背景颜色更改为清晰颜色,所以我看到全黑。我应该看看相机看到了什么。
答案 0 :(得分:7)
事实证明,您必须为预览图层设置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];