Make AVPlayer to full screen view in AVPlayerViewController, Swift

13,249

Solution 1

For adding AVPlayer to a view, I make a CALayer from it like this:

let playerLayer = AVPlayerLayer(player: player)

Then you need to add this layer to a view, for example, if you wrote that code in a ViewController, then you can do this:

self.view.layer.addSublayer(playerLayer)

Next, make sure that this layer is as big as the parent ViewController:

playerLayer.frame = self.view.layer.bounds

And now, you can choose any of these options to how to resize your video. Here, I used .resize assuming aspect ratio of video and the screen are the same

playerLayer.videoGravity = AVLayerVideoGravity.resize

Solution 2

I'd recommend following solution without adding extra layer:

in your ViewController: AVPlayerViewController in viewDidLoad() just set

videoGravity = .resizeAspectFill

According to documentation:

The video gravity determines how the video content is scaled or stretched within the bounds of the player view controller’s view. The player view controller supports the following video gravity values:

  • resizeAspect
  • resizeAspectFill
  • resize

The default value is resizeAspect.

Share:
13,249
Sulman Malik
Author by

Sulman Malik

Updated on July 24, 2022

Comments

  • Sulman Malik
    Sulman Malik almost 2 years

    I am new to swift and getting problem in making AVPlayerViewController.player go to full screen in ViewController: AVPlayerViewController

    here is code I am using in viewDidAppear to play the video

        let path = NSBundle.mainBundle().pathForResource("video", ofType: "mp4")!
        let url = NSURL(fileURLWithPath: path)
    
        let player = AVPlayer(URL: url)
        self.player = player
        self.showsPlaybackControls = false
        self.player!.play()
    

    I am making playBackControlls hidden, and required to make video view to full screen...

  • Sulman Malik
    Sulman Malik about 5 years
    @(Hamoon Jamshidi Meydandar) did you tried to have play controls with AVPlayerLayer to full screen?