Pra*_*les 3 video ios avplayer avplayerlayer
让AVPlayer视频内容显示在一个视图中的诀窍是什么?
我们使用以下AVPlayer代码,但屏幕上没有显示任何内容.我们知道视频在那里,因为我们能够使用MPMoviePlayerController显示它.
这是我们使用的代码:
AVAsset *asset = [AVAsset assetWithURL:videoTempURL];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item];
player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:player];
// layer.frame = self.view.frame;
[self.view.layer addSublayer:layer];
layer.backgroundColor = [UIColor clearColor].CGColor;
//layer.backgroundColor = [UIColor greenColor].CGColor;
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[player play];
Run Code Online (Sandbox Code Playgroud)
我们是否为当前视图设置了不正确的图层?
seo*_*seo 11
您需要设置图层的框架属性.例如:
self.playerLayer.frame = CGRectMake(0, 0, 100, 100)
Run Code Online (Sandbox Code Playgroud)
如果您尝试了这个并且它在视图控制器的视图中不起作用,则可能是您尝试将图层的frame属性设置为创建时的视图控制器frame或bounds属性.您需要在布局过程中设置播放器的框架,此时视图控制器将设置为其他内容.要做到这一点:{0, 0, 0, 0}AVPlayerLayerframe{0, 0, 0, 0}
如果您在自定义UIView(包括IB)中使用自动布局:
override func layoutSubviews() {
super.layoutSubviews()
//Match size of view
CATransaction.begin()
CATransaction.setDisableActions(true)
self.playerLayer.frame = self.bounds
CATransaction.commit()
}
Run Code Online (Sandbox Code Playgroud)
如果您在自定义UIViewController中使用自动布局:
override fun viewDidLayoutSubviews() {
//Match size of view-controller
CATransaction.begin()
CATransaction.setDisableActions(true)
self.playerLayer.frame = self.view.bounds
CATransaction.commit()
}
Run Code Online (Sandbox Code Playgroud)
这些CATransaction行将禁用图层帧更改上的隐式动画.如果您想知道为什么通常不需要它,那是因为默认情况下支持UIView的图层不会隐式动画.在这种情况下,我们使用非视图支持层(AVPlayerLayer)
最佳路径是通过界面构建向视图控制器添加新视图,并在新添加的视图上设置自定义类.然后创建该自定义视图类并实现layoutSubviews代码.
事实证明,AVPlayer 需要自己的上下文视图才能播放。
我们添加了此代码,现在视频可以播放。不幸的是,AVPlayer 没有与 MPMoviePlayerController 不同的内置控件。目前尚不清楚苹果为何不赞成使用具有非标准化视频播放选项的工具。
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0, 320.0f, 200.0f)];
layer.frame = self.view.frame;
[containerView.layer addSublayer:layer];
[self.view addSubview:containerView];
layer.backgroundColor = [UIColor greenColor].CGColor;
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[player play];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8842 次 |
| 最近记录: |