I'm trying to fit a video inside the view I've created on storyboard.
Here is how I added the view to my storyboard.
Here is how it shown in simulator. I want to fit the video inside of the view I've created.
func createVideoView() {
if let url = URL(string: self.videoUrl!) {
let player = AVPlayer(url: url)
let avController = AVPlayerViewController()
avController.player = player
// your desired frame
avController.view.frame = self.videoView.frame
self.view.addSubview(avController.view)
self.addChild(avController)
}
}
Also here is how I create the video. Notice that videoView variable is the view I want to show the video in.
CodePudding user response:
AVPlayerController
has attribute videoGravity
to set fill video and resizeAspectFill
is the one you need to set fill video on the screen. Notice that when you fill maybe it will not show correctly for all video.
func createVideoView() {
if let url = URL(string: "https://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v") {
let player = AVPlayer(url: url)
let avController = AVPlayerViewController()
avController.player = player
// your desired frame
avController.view.frame = self.videoView.frame
avController.videoGravity = .resizeAspectFill // here
self.view.addSubview(avController.view)
self.addChild(avController)
}
}
Beside, you should make the AVPlayer
as the subview of your videoView
so that you can handle easier than addSubView
to your viewController
.
func createVideoView() {
if let url = URL(string: "https://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v") {
let player = AVPlayer(url: url)
let avController = AVPlayerViewController()
avController.player = player
// your desired frame
avController.view.frame = self.videoView.bounds // change to bounds
avController.videoGravity = .resizeAspectFill // here
self.videoView.addSubview(avController.view) // add subview to videoView
self.addChild(avController)
}
}