videoGravity resizeAspectFill 不起作用 - Swift - AVFoundation

videoGravity resizeAspectFill doesn't work - Swift - AVFoundation

我在 UIView 中显示视频,一切正常,视频层边界与嵌入它的 UIView 相同。

问题是视频在视图边界内显示不正确,我只能看到它的一部分(正好是中心)。

所以我搜索了一下,发现有一个属性的AVPlayerLayer应该可以解决这个问题:.videoGravity

我用 .resizeAspectFill 实现了它,但它没有改变任何东西。

代码如下:

 class PlaceHolderVideoView : UIView{

  var player = AVPlayer()
  var playerLayer = AVPlayerLayer()
  let containerImageView = UIImageView(image: #imageLiteral(resourceName: "VideoContainerView"), contentMode: .scaleAspectFit)



override init(frame: CGRect) {
super.init(frame: frame)

setUpUI()

setUpPlayer()



}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

fileprivate func setUpUI(){
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false

addSubview(containerImageView)
containerImageView.clipsToBounds = true
containerImageView.fillSuperview()


}

fileprivate func setUpPlayer(){

let urlPathString = Bundle.main.path(forResource: "dance", ofType: "mp4")

if let videoURL = urlPathString{
    
    let url = URL(fileURLWithPath: videoURL)
    player = AVPlayer(url: url)
    playerLayer = AVPlayerLayer(player: player)
    playerLayer.cornerRadius = 20
    playerLayer.bounds = self.containerImageView.bounds
    print(self.containerImageView.bounds)
    playerLayer.videoGravity = .resizeAspectFill
    
    
    self.layer.masksToBounds = true
    self.layer.cornerRadius = 20
    self.layer.addSublayer(playerLayer)
    
    player.play()
    
    }
}
}

为了解决这个问题,我需要像这样调用 layoutSublayers 方法:

override func layoutSublayers(of layer: CALayer) {
    super.layoutSublayers(of: layer)
    
    playerLayer.frame = self.bounds
}

该方法可以正确设置playerLayer的bounds