Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayerLayer not bounds to UIView frame

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):

This is the view:

Constraints: Constraints:

Final result: enter image description here

I can't figure out why video is not bounds to UIVIew coordinates. If i bounds it into controller's superview, it is ok.

like image 356
Jornia Kabakum Avatar asked Feb 16 '16 21:02

Jornia Kabakum


2 Answers

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.

like image 112
almas Avatar answered Oct 31 '22 13:10

almas


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
    }
}
like image 26
AnBisw Avatar answered Oct 31 '22 12:10

AnBisw