我在UIView中显示一个视频,一切都很好,视频层边界与嵌入它的UIView是相同的。
问题是视频不能正确地显示在视图的边界内,我只能看到其中的一部分(准确地说是中心)。
所以我搜索了一下,发现AVPlayerLayer有一个属性可以解决这个问题:.videoGravity
我用.resizeAspectFill实现了它,但是它没有改变任何东西。
以下是代码:
class PlaceHolderVideoView : UIView{
var player = AVPlayer()
var playerLayer = AVPlayerLayer()
let containerImageView = UIImageView(image: #imageLiteral(resourceName: "VideoContainerView"), contentMode: .scaleAspectFit)
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
setUpPlayer()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setUpUI(){
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
addSubview(containerImageView)
containerImageView.clipsToBounds = true
containerImageView.fillSuperview()
}
fileprivate func setUpPlayer(){
let urlPathString = Bundle.main.path(forResource: "dance", ofType: "mp4")
if let videoURL = urlPathString{
let url = URL(fileURLWithPath: videoURL)
player = AVPlayer(url: url)
playerLayer = AVPlayerLayer(player: player)
playerLayer.cornerRadius = 20
playerLayer.bounds = self.containerImageView.bounds
print(self.containerImageView.bounds)
playerLayer.videoGravity = .resizeAspectFill
self.layer.masksToBounds = true
self.layer.cornerRadius = 20
self.layer.addSublayer(playerLayer)
player.play()
}
}
}
发布于 2020-07-13 00:18:16
为了解决这个问题,我需要像这样调用layoutSublayers方法:
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
playerLayer.frame = self.bounds
}
该方法可以正确地设置playerLayer的边界。
https://stackoverflow.com/questions/62861737
复制相似问题