o2webdev o2webdev - 3 years ago 144
Swift Question

AVPlayer video is not fitting horizontal

Building my first app and trying to fit the background video horizontal.

Below is the code l'm using

override func viewDidLoad()
{
super.viewDidLoad()

let URL = Bundle.main.url(forResource: "homedocapp", withExtension: "mp4")

Player = AVPlayer.init(url: URL!)

PlayerLayer = AVPlayerLayer(player: Player)
PlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
PlayerLayer.frame = self.view.frame; PlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
PlayerLayer.zPosition = -1

Player.actionAtItemEnd = AVPlayerActionAtItemEnd.none

self.view.layer.addSublayer(PlayerLayer)

Player.play()

view.layer.insertSublayer(PlayerLayer, at: 0)

NotificationCenter.default.addObserver(self, selector: #selector(playerItemReachEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: Player.currentItem)


}


AVPlayer Horizontal display

Thank you in advances

Answer Source

When 'viewDidLoad' is called, view still can have incorrect size. So your PlayerLayer will have incorrect size as well. Try to move your code to the 'viewDidLayoutSubviews' function:

override func viewDidLayoutSubviews() 
{
    super.viewDidLayoutSubviews()

    // Set up your player layer instance here
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download