Reputation: 5
I'm trying to display video in the background. Red parts fill up all of the screen. How can I achieve, so there will be no red filling up space and the size of the view will equal content size?
// VideoPlayerUIView is a UIViewControllerRepresentable for AVPlayer
struct VideoPlayerUIView: UIViewControllerRepresentable {
let player: AVPlayer
func makeUIViewController(context: Context) -> UIViewController {
let controller = UIViewController()
let playerLayer = AVPlayerLayer(player: player)
// Set the video to fill the screen
playerLayer.videoGravity = .resizeAspect
playerLayer.frame = UIScreen.main.bounds
controller.view.layer.addSublayer(playerLayer)
return controller
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
// This is how I display it
VideoPlayerUIView(player: player1)
.background(.red)
Upvotes: 0
Views: 65
Reputation: 11
Based on how I understand your problem:
If you want the video to take up the whole screen, replace playerLayer.videoGravity = .resizeAspect
with playerLayer.videoGravity = .resizeAspectFill
If you want to match size of the view with its content, try using VideoPlayerUIView(player: player1).scaledToFit()
(PlayerView() is a UIViewControllerRepresentable, like OP)
Without scaledToFit()
: https://i.sstatic.net/82nL068T.png
var body: some View {
PlayerView()
// .scaledToFit()
.background(.red)
}
With scaledToFit()
: https://i.sstatic.net/jt1OjXMF.png
var body: some View {
PlayerView()
.scaledToFit()
.background(.red)
}
Upvotes: 1