首页 > 解决方案 > 使用 AVPlayer 调整视图底部的视频

问题描述

我是 iOS 世界的新手,我遇到了一个我不知道如何处理的案例。

我有一个 mp4 视频,我用 AVPlayer 在视图中显示,我的问题是它总是出现在视图的中心部分。我想要做的是将它放在视图的底部。我怎样才能做到这一点?

我留下我正在使用的代码,它是 AVPlayer 的基本实现。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: videoName, ofType: "mp4")!))
    let layer = AVPlayerLayer(player: player)
    layer.frame = view.bounds
    view.layer.addSublayer(layer)
    player.play()
}

标签: iosswiftavplayerswift5

解决方案


您正在使用 Avplayerlayer 的主视图框架。这会导致它占用整个屏幕。使用此功能将视频添加到您的视图底部。

 func addvideoToBottom(heightPercent value:CGFloat ) {
    let bottomView = UIView()
    bottomView.backgroundColor = .black
    self.view.addSubview(bottomView)
    bottomView.translatesAutoresizingMaskIntoConstraints = false
    bottomView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
    bottomView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
    bottomView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
    bottomView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: value).isActive = true
    bottomView.layoutIfNeeded()
    let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "video", ofType: "mp4")!))
    let layer = AVPlayerLayer(player: player)
    layer.frame = bottomView.bounds
    bottomView.layer.addSublayer(layer)
    player.play()
}

并从您的viewdidAppear 中像这样调用此函数

addvideoToBottom(heightPercent: 0.3)

0.3 表示视频帧高度为手机屏幕的 30%。根据您的要求, heightPercent应介于 0 和 1 之间。


推荐阅读