gpt4 book ai didi

swift - 如何将 AVPlayerLayer 显示为全屏?

转载 作者:行者123 更新时间:2023-11-28 11:27:05 24 4
gpt4 key购买 nike

在 Main.storyboard 窗口中添加了一个 View Controller 组件。

enter image description here

View as: Iphone8 选项在 Main.storyboard 窗口中被选中

enter image description here

TestViewController.swift 文件已创建并显示为引用:

enter image description here

UIView 组件已添加

enter image description here

UIView 组件添加约束:

enter image description here

UIView 的背景颜色改变了:

enter image description here

outlet 是为 UIView 创建的:

enter image description here

然后下面的代码写在TestViewController.swift文件中

import UIKit
import AVFoundation
import AVKit

class TestViewController: UIViewController {

private var player: AVPlayer!
@IBOutlet weak var videoUiViewOutlet: UIView!

override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}

private func setupView()
{
let path = URL(fileURLWithPath: Bundle.main.path(forResource: "clouds", ofType: "mp4")!)
let player = AVPlayer(url: path)
self.player = player
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoUiViewOutlet.frame
self.videoUiViewOutlet.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

player.play()

player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none

NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidPlayToEnd(notification:)),
name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem)

NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(enteredForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}

@objc func videoDidPlayToEnd(notification: Notification)
{
let player: AVPlayerItem = notification.object as! AVPlayerItem
player.seek(to: .zero, completionHandler: nil)
}

@objc func enteredBackground() {
player.pause()
}

@objc func enteredForeground() {
player.play()
}
}

然后应用程序在 Iphone 8 Plus 中运行。这是 Iphone 8 Plus 的屏幕截图:

enter image description here

我的问题:我希望在所有设备上全屏观看视频。我该如何解决这个问题?

最佳答案

您需要在 viewDidLayoutSubviews 中设置 frame,其中存在正确的 bounds

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
newLayer.frame = self.videoUiViewOutlet.bounds
}

关于swift - 如何将 AVPlayerLayer 显示为全屏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com