I have a UIView
which contains an AVPlayer
to show a video. When changing orientation, I need to change the size and location of the video.
I'm not very experienced with resizing layers, so I'm having problems making the video resize.
I start by creating the AVPlayer
and adding its player to my videoHolderView's layer:
NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
self.avPlayer = [AVPlayer playerWithURL:videoURL];
AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
playerLayer.frame = videoHolderView.bounds;
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
playerLayer.needsDisplayOnBoundsChange = YES;
[videoHolderView.layer addSublayer:playerLayer];
videoHolderView.layer.needsDisplayOnBoundsChange = YES;
Then, at a later point, I change the size and location of the videoHolderView's frame:
[videoHolderView setFrame:CGRectMake(0, 0, 768, 502)];
At this point, I need the avPlayer to resize to these same dimension. This doesn't happen automatically - the avPlayer stays at it's small size within the videoHolderView.
If anyone can help, I'd really appreciate any advice.
Thanks guys.
You can change the layer's frame by overriding the
-layoutSubviews
method:Actually you shouldn't add AVPlayer's layer as a sublayer. Instead of that you should use the following method, in the subclass of view in which you want to display AVPlayer.
And use the following line to add(set) the player layer.
Hope it helps;-)
Converting @Suran's solution to Swift 3:
First, create a class inheriting UIView where you override only 1 variable:
Then add a simple UIView using the interface builder and change its class to the one you just created: AVPlayerView
Then, make an outlet for that view. Call it avPlayerView
Now, you can use that view inside your viewcontroller and access its avlayer like this:
The layer will now follow the constraints just like a regular layer would do. No need to manually change bounds or sizes.
Any one searching for Xamarin Version as i was searching
don't add the AVPlayerLayer as sublayer but set the layer to Avplayer Layer
The following line set the layer
theDunc's answer did not work for me. I found a solution that is more simple: I just needed to adjust the frame of the AVPlayerLayer after changing it in the UIView:
In this blog is stated, that a View's frame also affect that of the layer in it.
For this case, it is not true.
In the end I solved this by re-adding the AVPlayerLayer to the UIView. I'm not sure why changing the frame removed the layer, but it did. Here's the final solution: