我有一个自定义的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()
}
}
我显然没有做正确的事情,或者根据我的最终结果我遗漏了一些东西。有什么线索吗?
更新:
我注意到,如果缓慢滚动单元格,视频将根据缩略图的大小显示。但如果你快速滚动,它就会与框架不匹配。我认为它与可重用性有关,或者它根本无法 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/