使用AutoLayout设置AVPlayer/AVPlayerLayer大小?

问题描述 投票:0回答:1

我正在尝试使用自动布局设置在视图中显示的视频的大小/帧。但我不知道如何正确地做到这一点。这是我的观点的代码:

import UIKit
import AVKit

class VideoMeetingView: UIView {

    lazy var playerLayer: AVPlayerLayer = {
        let layer = AVPlayerLayer()
        return layer
    }()

    private lazy var videoView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .blue
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
        self.addSubviewsAndConstraints()

        playerLayer.frame = videoView.bounds
        videoView.layer.addSublayer(playerLayer)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func addSubviewsAndConstraints() {
        self.addSubview(videoView)

        videoView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        videoView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        videoView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        videoView.heightAnchor.constraint(equalToConstant: 600).isActive = true
    }

}

如果我打印出

videoView.bounds
的值,它只是
(0, 0, 0, 0)
,所以我猜 AutoLayout 不会像我首先想到的那样更新值。

如果我使用

playerLayer.frame
手动设置
CGRect
的大小,一切都会正常工作。但我想使用自动布局。

那么如何使用 AutoLayout 设置

AvPlayerLayer
的大小?

ios swift avplayer avplayerlayer
1个回答
20
投票

做:

self.playerLayer = {
   let layer = AVPlayerLayer(player: self.player)
    layer.videoGravity = .resizeAspect
    layer.needsDisplayOnBoundsChange = true
    return layer
}()

当其父级的边界发生变化时,这会导致图层调整宽高比以适应。

此外,您可能还需要添加:

override func layoutSubviews() {
    super.layoutSubviews()

    self.playerLayer.frame = self.bounds
}

这样无论如何它都有正确的框架..

另一种选择是使

AVPlayerLayer
成为
UIView
本身的实际层,而不是子层:

class VideoView : UIView
{
    override var layer: CALayer {
        return AVPlayerLayer.class
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.