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

问题描述 投票:2回答:2

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

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
    }

}
swift uiview avplayer avplayerlayer
2个回答
4
投票

尝试使用来自sizeviewWillTransition,这样做:

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

0
投票

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

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
      }
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.