AVCaptureVideoPreviewLayer *avLayer =
[AVCaptureVideoPreviewLayer layerWithSession:session];
avLayer.frame = self.view.frame;
[self.view.layer addSublayer:avLayer];
我使用AVCaptureVideoPreviewLayer在视图上显示视频。 但视频的视图并没有填满整个iPhone4的屏幕。(右侧和左侧有两个灰色条)
我希望视频能够全屏显示。 我怎么处理它?非常感谢你!
答案 0 :(得分:185)
也许这解决了?
CGRect bounds=view.layer.bounds;
avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
avLayer.bounds=bounds;
avLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
答案 1 :(得分:13)
混淆的一个潜在原因是AVCaptureVideoPreviewLayer
是CoreAnimation层,并且在上面的所有答案中,相对于视图静态地(例如,没有约束)定位。如果使用约束来布局视图,则不会自动调整预览图层的大小。
这意味着您无法在viewDidLoad
中设置预览图层,因为尚未进行布局,预览图层将按照界面生成器的大小进行调整。
相反,覆盖viewDidLayoutSubviews
上的ViewController
并将预览图层放在那里。
- (void)viewDidLayoutSubviews
{
CGRect bounds=view.layer.bounds;
avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
avLayer.bounds=bounds;
avLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
}
答案 2 :(得分:11)
@ fitzwald的答案将为您提供所需的结果,但有一种更简单的方法。发生的事情是会话预设默认为视频 - 高(与屏幕的宽高比不匹配)。使用Photo预设可以实现全屏预览(如在Camera.app中)。只需设置
session.sessionPreset = AVCaptureSessionPresetPhoto;
在开始会话之前。如果您想了解更多信息,请参阅Apple Documentation。
答案 3 :(得分:8)
出于谷歌的考虑,这是接受的答案,但使用的Swift略有不同:
var bounds:CGRect = self.view.layer.bounds
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer?.bounds = bounds
previewLayer?.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
答案 4 :(得分:3)
接受的答案
斯威夫特3:
let bounds = view.layer.bounds
self.cameraLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.cameraLayer.bounds = bounds
self.cameraLayer.position = CGPoint(x:bounds.midX, y:bounds.midY)
self.cameraView?.layer.addSublayer(self.cameraLayer)
Swift 4:
let bounds = view.layer.bounds
self.cameraLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.cameraLayer.bounds = bounds
self.cameraLayer.position = CGPoint(x:bounds.midX, y:bounds.midY)
self.cameraView?.layer.addSublayer(self.cameraLayer)
答案 5 :(得分:1)
我使用以下代码来实现此目的
previewLayer.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
previewLayer.orientation = [[UIDevice currentDevice] orientation];
previewLayer.contentsGravity = kCAGravityResizeAspectFill;
答案 6 :(得分:0)
雨燕5
我通过使用以下代码解决了这个问题:
let bounds = view.layer.bounds
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(previewLayer)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
previewLayer.bounds = bounds
previewLayer.position = CGPoint(x:bounds.midX, y:bounds.midY)