AVPlayerLayer大小不正确

时间:2018-10-23 12:04:24

标签: ios swift uiimageview avplayer avplayerlayer

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

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

enter image description here

这是我的方法:

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

1 个答案:

答案 0 :(得分:0)

该解决方案非常简单。基本上,每个帖子都包含帖子或视频,但是无论哪种方式,它总是包含图像。我还设置了该图像的ratio(由width划分的height)。因此,我要做的就是将播放器的width设置为由比率指定的屏幕宽度,它会为您提供适当的帧。

playerLayer.frame.size.height = UIScreen.main.bounds.width / postRatio
相关问题