thelearner
thelearner

Reputation: 1130

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

Upvotes: 1

Views: 1758

Answers (2)

thelearner
thelearner

Reputation: 1130

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.

Upvotes: 0

a.masri
a.masri

Reputation: 2469

Try this steps

1- Check bottom constraint connect with safe are

enter image description here

2- Try this code

import UIKit
import AVKit

class ViewController: UIViewController {
    @IBOutlet weak var playerView: UIView!
    private var player: AVPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
       playVideo(from: "Intro.mp4")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    private func playVideo(from file:String) {
        let file = file.components(separatedBy: ".")

        guard let path = Bundle.main.path(forResource: file[0], ofType:file[1]) else {
            debugPrint( "\(file.joined(separator: ".")) not found")
            return
        }

        player = AVPlayer(url: URL(fileURLWithPath: path))

        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { _ in
            self.player?.seek(to: kCMTimeZero)
            self.player?.play()
        }

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
        playerLayer.frame = playerView.layer.bounds
        playerView.layer.insertSublayer(playerLayer, at: 0)
        player.play()
    }

}

Result on iphone X

enter image description here

Result on iphone 7

enter image description here

Note : if you need video full view on all devices try to link Bottom constraint and Top constraint with superview not with safe area

Upvotes: 1

Related Questions