我正在尝试对连接到系统的设备进行iOS屏幕录制。我有一个NSView,它包含AVCaptureView类型的videoView。我在videoView中添加了一个sublayer(previewLayer),它显示了视频帧的预览。我试图根据从iOS屏幕录制得到的视频的第一帧大小来保持previewLayer和videoView的宽高比
- (void)captureOutput:(AVCaptureFileOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection
{
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
if(imageBuffer != NULL)
{
CGSize imageSize = CVImageBufferGetDisplaySize(imageBuffer);
NSLog(@"imageSize = %@", NSStringFromSize(imageSize));
CGRect bounds = CGRectZero;
bounds.size = imageSize;
CGRect superViewBounds = streamingView.bounds;
NSLog(@"superViewBounds = %@", NSStringFromRect(superViewBounds));
if(bounds.size.width>superViewBounds.size.width || bounds.size.height>superViewBounds.size.height)
{
CGFloat ratio_width = bounds.size.width/superViewBounds.size.width;
CGFloat ratio_height = bounds.size.height/superViewBounds.size.height;
CGFloat ratio;
if (ratio_width > ratio_height)
{
ratio = ratio_width;
}
else
{
ratio = ratio_height;
}
bounds.size.width = bounds.size.width/ratio;
bounds.size.height = bounds.size.height/ratio;
bounds.origin.x = CGRectGetMidX(superViewBounds)-CGRectGetMidX(bounds);
bounds.origin.y = CGRectGetMidY(superViewBounds)-CGRectGetMidY(bounds);
NSLog(@"bounds calculation = %@", NSStringFromRect(bounds));
}
[self.previewLayer setFrame:bounds];
NSLog(@"preview layer = %@", NSStringFromRect(self.previewLayer.frame));
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.previewLayer setBackgroundColor:CGColorGetConstantColor(kCGColorWhite)];
[_videoView setFrame:bounds];
}
}

输出
图像1 - 在纵向模式下第一次加载视图时 图2 - 当iOS设备方向更改为横向模式时 图3 - 当iOS设备朝向纵向模式时
如果设备保持原样而不改变方向 我得到以下日志
CoreAnimation:警告,删除线程与未提交的CATransaction;在环境中设置CA_DEBUG_TRANSACTIONS = 1以记录回溯。
然后在更改设备的方向时,它显示如下