ios - AVPlayerLayer 大小不正确

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

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

更新: 我注意到,如果缓慢滚动单元格,视频将根据缩略图的大小显示。但如果你快速滚动,它就会与框架不匹配。我认为它与可重用性有关,或者它根本无法 catch 框架?这是我的 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()
    }
}

最佳答案

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

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

关于ios - AVPlayerLayer 大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52948667/

相关文章:

ios - 处理带有从挂起状态返回的身份验证 token 的 iOS 应用程序的最佳方法是什么?

ios - 如何使用对象数组填充 TableView?

ios - swift - 使用 replaceRange() 来更改字符串中的特定事件

swift - Swift 初学者,错误 UIPicker

ios - 顶部导航栏已禁用

ios - 确定 UIImageView 花费的时间 'drawing' 的方法?

ios - 带有包含 UIImageView 的 UITableViewCell 的 UITableView

swift - “JSON 写入 (UIImage) 中的类型无效”Alamofire API 请求

ios - 收集字符串值并添加到数组中

ios - 如何更改 UISearchBar 内文本字段的位置