在设置AVCaptureVideoPreviewLayer时,需要设置layer的videoGravity属性为AVLayerVideoGravityResizeAspectFill,并根据设备的方向进行调整。
示例代码:
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
previewLayer.frame = self.view.bounds;
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait) {
previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
} else if (orientation == UIDeviceOrientationPortraitUpsideDown) {
previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
} else if (orientation == UIDeviceOrientationLandscapeLeft) {
previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
} else if (orientation == UIDeviceOrientationLandscapeRight) {
previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
}
[self.view.layer addSublayer:previewLayer];