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.
Found a great article by Marco Santarossa that shows multiple approaches to fixing. https://marcosantadev.com/calayer-auto-layout-swift/
I used his first suggestion to reset the layer frame during viewDidLayoutSubViews() event.
I had this problem in Swift 2.3, and I solved writing a proper PlayerView class and setting it as subview:
In the presenting ViewController:
To get to
playerLayer
, you need to loop throughvideoHolderView.layer.sublayers
and change each one.this is what I did in Swift 2.2
For those of you who are only concerned with resizing the AVPlayer during device rotation, you can alter your layer frame in the viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) method as shown below.
This will animate your layer frame along with all the other views during the rotation.
First step: check out UIView's autoresizing property in UIVIew.h
This property correspondents to the "springs and struts" controls in IB, though it will take you some experimentation to get the results you want.