我试图在设备旋转后使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
}
}
尝试使用来自size
的viewWillTransition
,这样做:
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
是对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
}
}
}