I'm trying to add AVPlayerLayer to UIView
self.player = AVPlayer(URL: NSURL(fileURLWithPath: path!))
self.playerLayer = AVPlayerLayer(player: player);
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.playerLayer.frame = ctrVideo.bounds;
self.ctrVideo.layer.addSublayer(playerLayer);
player.play();
This is the video's container (in blue):
Constraints:
Final result:
I can't figure out why video is not bounds to UIVIew coordinates. If i bounds it into controller's superview, it is ok.
Sublayer won't resize automatically when view's frame changes, you have to do it manually. You can subclass a UIView to make it easier.
class VideoContainerView: UIView {
var playerLayer: CALayer?
override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
playerLayer?.frame = self.bounds
}
}
And then in your code:
self.player = AVPlayer(URL: NSURL(fileURLWithPath: path!))
self.playerLayer = AVPlayerLayer(player: player);
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.playerLayer.frame = ctrVideo.bounds;
self.ctrVideo.layer.addSublayer(playerLayer);
self.ctrVideo.playerLayer = playerLayer;
player.play();
Just make sure that you change that class of your "ctrVideo" from UIView to VideoContainerView.
Here's @almas' awesome answer in Swift 4
class VideoContainerView: UIView {
var playerLayer: CALayer?
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
playerLayer?.frame = self.bounds
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With