UIView框架更改时,视图内的AVPlayer图层不会调整大小 [英] AVPlayer layer inside a view does not resize when UIView frame changes
问题描述
我有一个UIView
,其中包含一个AVPlayer
来显示视频.更改方向时,我需要更改视频的大小和位置.
I have a UIView
which contains an AVPlayer
to show a video. When changing orientation, I need to change the size and location of the video.
我对调整图层的大小不是很有经验,因此在调整视频大小时遇到了问题.
I'm not very experienced with resizing layers, so I'm having problems making the video resize.
我首先创建AVPlayer
并将其播放器添加到我的videoHolderView层:
I start by creating the AVPlayer
and adding its player to my videoHolderView's layer:
NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
self.avPlayer = [AVPlayer playerWithURL:videoURL];
AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
playerLayer.frame = videoHolderView.bounds;
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
playerLayer.needsDisplayOnBoundsChange = YES;
[videoHolderView.layer addSublayer:playerLayer];
videoHolderView.layer.needsDisplayOnBoundsChange = YES;
然后,稍后,我更改videoHolderView框架的大小和位置:
Then, at a later point, I change the size and location of the videoHolderView's frame:
[videoHolderView setFrame:CGRectMake(0, 0, 768, 502)];
这时,我需要avPlayer调整为这些相同的尺寸.这不会自动发生-avPlayer在videoHolderView中保持很小的尺寸.
At this point, I need the avPlayer to resize to these same dimension. This doesn't happen automatically - the avPlayer stays at it's small size within the videoHolderView.
如果有人可以提供帮助,我将非常感谢您提供任何建议.
If anyone can help, I'd really appreciate any advice.
谢谢大家.
推荐答案
最后,我通过将AVPlayerLayer重新添加到UIView来解决了这个问题.我不确定为什么更改框架会删除图层,但是确实如此.这是最终的解决方案:
In the end I solved this by re-adding the AVPlayerLayer to the UIView. I'm not sure why changing the frame removed the layer, but it did. Here's the final solution:
//amend the frame of the view
[videoHolderView setFrame:CGRectMake(0, 0, 768, 502)];
//reset the layer's frame, and re-add it to the view
AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
playerLayer.frame = videoHolderView.bounds;
[videoHolderView.layer addSublayer:playerLayer];
这篇关于UIView框架更改时,视图内的AVPlayer图层不会调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!