当 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.
谢谢各位.
推荐答案
将@Suran 的解决方案转换为 Swift:
Converting @Suran's solution to Swift:
首先,创建一个继承 UIView 的类,您只覆盖 1 个变量:
First, create a class inheriting UIView where you override only 1 variable:
import UIKit
import AVFoundation
class AVPlayerView: UIView {
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
然后使用界面构建器添加一个简单的 UIView 并将其类更改为您刚刚创建的类:AVPlayerView
Then add a simple UIView using the interface builder and change its class to the one you just created: AVPlayerView
然后,为该视图创建一个出口.称之为avPlayerView
Then, make an outlet for that view. Call it avPlayerView
@IBOutlet weak var avPlayerView: AVPlayerView!
现在,您可以在视图控制器中使用该视图并像这样访问其 avlayer:
Now, you can use that view inside your viewcontroller and access its avlayer like this:
let avPlayer = AVPlayer(url: video)
let castLayer = avPlayerView.layer as! AVPlayerLayer
castLayer.player = avPlayer
avPlayer.play()
该层现在将像常规层一样遵循约束.无需手动更改边界或大小.
The layer will now follow the constraints just like a regular layer would do. No need to manually change bounds or sizes.
这篇关于当 UIView 框架更改时,视图内的 AVPlayer 层不会调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!