使用AutoLayout设置AVPlayer / AVPlayerLayer大小?

时间:2018-01-05 15:45:19

标签: ios swift avplayer avplayerlayer

我尝试使用AutoLayout设置我在视图中显示的视频的大小/帧。但我无法弄清楚如何正确地做到这一点。这是我的观点的代码:

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。

那么如何使用AutoLayout设置AvPlayerLayer的大小?

1 个答案:

答案 0 :(得分:7)

执行:

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
    }
}