Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make AVPlayer fill the entire screen

I have an app where I'd like a video to play in the background of a single view.

What I did is create an AVPlayer, add that to an AVPlayerLayer and add that as a sublayer to my view.

Then I set the frame and the videoGravity property:

self.player = AVPlayer(url: URL(fileURLWithPath: path))
let playerLayer = AVPlayerLayer(player: self.player)
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.bounds
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

Now the video plays, except it doesn't fill the entire screen. It fills it's original size, but it doesn't stretch/scale.

Am I missing something? Why is my video not resizing?

Thanks.

Edit:

I added a screenshot and made the view purple for easier reference.

Screenshot

like image 421
ilikecode Avatar asked Jan 29 '18 21:01

ilikecode


2 Answers

If you want to video to be stretch on the entire view, just delete the line

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

videoGravity default value is AVLayerVideoGravityResize

Update for Swift 5

playerLayer.videoGravity = .resizeAspectFill
like image 188
Tal Cohen Avatar answered Oct 11 '22 00:10

Tal Cohen


Define the playerLayer.frame inside viewDidLayoutSubviews()

At the time you are defining the frames the final frames for the views were not yet calculated.

like image 3
andrehungaro Avatar answered Oct 11 '22 02:10

andrehungaro