Swift AV Player视频应为AspectFill或全屏

时间:2018-08-21 12:22:54

标签: ios iphone swift avplayer avplayerviewcontroller

在“登录”屏幕上,我必须以全分辨率显示背景视频。我可以通过双击下面黑色区域的图像来做到这一点。

enter image description here

这是我要求的结果。但这不是通过编码完成的。我只是通过双击黑色区域来做到这一点。 enter image description here

这是我这堂课的代码。

class loginViewController: UIViewController {
@IBOutlet weak var videoView: UIView!
let player = AVPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = true
    let myFileManager = FileManager.default
    let mainBundle = Bundle.main
    let resourcesPath = mainBundle.resourcePath!
    guard let allItemsInTheBundle = try? myFileManager.contentsOfDirectory(atPath: resourcesPath) else {
        return
        }

    let videoName = "login_video"
    let videoPath = Bundle.main.path(forResource: videoName, ofType: "mp4")
    let videoUrl = URL(fileURLWithPath: videoPath!)

        let player = AVPlayer(url: videoUrl)
        let controller=AVPlayerViewController()
        controller.player=player

        let playerLayer = AVPlayerLayer(player: self.player)        
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill;

        controller.showsPlaybackControls = false
        controller.view.frame = self.view.frame
        videoView.addSubview(controller.view)
        self.addChildViewController(controller)
        player.play()
        player.actionAtItemEnd = .none
        loopVideo(player: player)
}
func loopVideo(player: AVPlayer) {
    NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) { notification in
        player.seek(to: kCMTimeZero)
        player.play()
    }
}   
}

有人可以建议我如何实现所需的结果。我找到了这个解决方案,但有意思。

     let playerLayer = AVPlayerLayer(player: self.player)        
     playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill;

请给我建议更好的方法。 预先感谢。

1 个答案:

答案 0 :(得分:3)

此代码不执行任何操作:

    let playerLayer = AVPlayerLayer(player: self.player)        
    playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill;

所有要做的就是创建一个新的播放器层并将其丢弃。

AVPlayerViewController已经具有一个播放器层!设置AVPlayerViewController的视频重力。

    controller.videoGravity = ...