AVPlayerLayer 的大小不正确

达尼

我有一个自定义UITableViewCell显示图像或视频。如果有视频,它最初会在视频加载和准备播放时下载并显示该视频的缩略图。

一切正常,问题是我获得了缩略图的比例,将其存储在数据库中,当我下载缩略图时,它会根据该比例确定高度。它适用于图像。但问题是AVPlayerLayer框架没有覆盖整个缩略图,它看起来像这样:

在此处输入图片说明

这是我的方法:

 func updateView() {

    if let videoUrlString = post?.videoUrl, let videoUrl = URL(string: videoUrlString) {
        volumeView.isHidden = false
        player = AVPlayer(url: videoUrl)
        playerLayer = AVPlayerLayer(player: player)
        playerLayer!.frame = postImageView.frame // thumbnail image
        playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
        contentView.layer.addSublayer(playerLayer!)
        self.volumeView.layer.zPosition = 1
        layoutIfNeeded()
        player?.play()
        player?.isMuted = videoIsMuted
    }

    if let ratio = post?.ratio {
        photoHeightConstraint.constant = UIScreen.main.bounds.width / ratio
        layoutIfNeeded()
    }
 }

我显然没有做对的事情,或者根据我的最终结果,我遗漏了一些东西。有什么线索吗?

更新:我注意到,如果您缓慢滚动单元格,视频将根据缩略图的大小显示。但是如果你快速滚动,它会与框架不匹配。我认为它与可重用性有关,或者它根本无法赶上框架?这是我的prepareForReuse()方法代码

    override func prepareForReuse() {
    super.prepareForReuse()
    profileImageView.image = UIImage(named: "placeholder")
    postImageView.image = UIImage(named: "profile_placeholder")
    volumeView.isHidden = true
    if let p = player, let pLayer = playerLayer {
        p.pause()
        pLayer.removeFromSuperlayer()
    }
}
达尼

结果证明解决方案相当简单。基本上每个帖子都包含帖子或视频,但无论哪种方式,它总是包含一个图像。我还设置了ratio该图像的(width划分height)。所以,我所要做的就是将播放器设置为width屏幕宽度除以比例,它会为您提供正确的框架。

playerLayer.frame.size.height = UIScreen.main.bounds.width / postRatio

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章