Search code examples
iosswiftavfoundationavcompositionavvideocomposition

AVPlayer resizeAspect works only properly on iPhone X


resizeAspect as the video gravity only works properly for me, when using an iPhone X.

For some reasons, the black aspect bar gets only added to the top and not to the bottom. This is how it looks like when I'm not using an iPhone X (the image is white)

iphone

This is how it should look like:

normal state

As you can see, on the iPhone X, everything looks clean and balanced as expected.

This is how I play the video:

    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.frame = PreviewLayer.bounds
    avPlayerLayer.videoGravity = .resizeAspect //Will automatically add black bars


    PreviewLayer.layer.insertSublayer(avPlayerLayer, at: 0)
    let playerItem = AVPlayerItem(url: video)
    avPlayer?.replaceCurrentItem(with: playerItem)
    avPlayer?.play()

Solution

  • Make your videoLayer View a subview of:

    class VideoContainerView: UIView {
    
        var playerLayer: CALayer?
    
        override func layoutSublayers(of layer: CALayer) {
            super.layoutSublayers(of: layer)
            playerLayer?.frame = self.bounds
        }
    
    }
    

    and add:

    self.VideoShareLayer.playerLayer = avPlayerLayer;
    

    before inserting the layer.