【问题标题】:AVPlayerLayer not sizing correctlyAVPlayerLayer 尺寸不正确
【发布时间】:2018-10-23 12:04:24
【问题描述】:

我有一个自定义的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()
    }
}

【问题讨论】:

  • 尝试 playerLayer!.frame = contentView.bounds 而不是 playerLayer!.frame = postImageView.frame。看在上帝的份上,应用可选链,它看起来会更好:)
  • @T.Pasichnyk 但这并没有改变问题。视频应该与缩略图在同一帧,但事实并非如此。所以你可以看到缩略图的底部,上面是视频
  • 缩略图和视频帧大小一样吗?
  • @T.Pasichnyk 不,它们的尺寸似乎不同,我不明白为什么
  • 那你应该先搞清楚这个

标签: ios swift uiimageview avplayer avplayerlayer


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多