RinaredTap
RinaredTap

Reputation: 5

Video fills up all of the space (AVPlayer, UIViewControllerRepresentable, SwiftUI)

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)
 

2

Upvotes: 0

Views: 65

Answers (1)

UnstoppableWil
UnstoppableWil

Reputation: 11

Based on how I understand your problem:

  1. If you want the video to take up the whole screen, replace playerLayer.videoGravity = .resizeAspect with playerLayer.videoGravity = .resizeAspectFill

  2. 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

Related Questions