我试图让 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
}
}
关于swift - AVPlayer 视频在设备旋转后不调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686950/