AVPlayer 视频在设备旋转后不调整大小

AVPlayer video doesn't resize after device rotation

我正在尝试让 AVPlayer 视频在设备旋转后始终全屏显示。这是我的完整代码。我不明白为什么视频没有调整大小。即使我使用像 layerClass 这样的子类。设备旋转后 videoView 被剪切,我看不到完整的视频。如果有人有想法。提前致谢。

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVPlayer?
    var videoView: VideoContainerView!
    var playerLayer: AVPlayerLayer!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.videoView = VideoContainerView()
        self.videoView.frame = self.view.bounds
        self.videoView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        let path = Bundle.main.path(forResource: "GAVIDEO", ofType: "mp4")
        self.player = AVPlayer(url: NSURL(fileURLWithPath: path!) as URL)
        self.player?.isMuted = true

        self.playerLayer = AVPlayerLayer(player: self.player)
        self.playerLayer.frame = self.videoView.bounds
        self.playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

        self.videoView.layer.addSublayer(playerLayer)

        self.videoView.layer.masksToBounds = true

        self.view.addSubview(self.videoView)

        self.player?.play()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        self.videoView.frame = self.view.bounds
        self.playerLayer.frame = self.videoView.bounds

    }

}

class VideoContainerView: UIView {

    override class var layerClass: AnyClass {
        get {
            return AVPlayerLayer.self
        }
    }

    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        guard layer == self.layer else {
            return
        }
        layer.frame = self.bounds
    }

}

尝试使用 viewWillTransition 中的 size,这样做:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
   super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: { (context) in
    }) { (context) in
        self.videoView.frame.size = size
        self.playerLayer.frame.size = size
    }
}

以下对我有用,其中 vc 是对包含您要调整大小的 AVPlayer 视图的 AVPlayerViewController 的引用。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
   super.viewWillTransition(to: size, with: coordinator)
   coordinator.animate(alongsideTransition: nil) { (context) in
      if size.height <= vc.view.bounds.height || size.width <= vc.view.bounds.width {
         vc.videoGravity = .resizeAspect
      }
      else {
         vc.videoGravity = .resizeAspectFill
      }
   }
}