Home > Blockchain >  SwiftUI, How to resize a video to fill all vertical (iPhone) while maintaining aspect ratio (left an
SwiftUI, How to resize a video to fill all vertical (iPhone) while maintaining aspect ratio (left an

Time:10-09

I have a video that is suitable for viewing on a tv or laptop (i.e. landscape dominant). I need to make this video fill an iPhone screen vertically without stretching the video out of aspect. Consequently much of the left and right of the video will bleed off the left and right sides of the screen.

CodingWithChris did exactly this in storyboard form here: screenshot of video

Thank you so much for your help!!

CodePudding user response:

Assuming your video's aspect ratio is 16:9, something like this would work:

struct ContentView: View {
    private let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "mov1", ofType: "mov")!))
    
    var body: some View {
        ZStack {
            GeometryReader { proxy in
                VideoPlayer(player: player)
                    .ignoresSafeArea()
                    .frame(width: proxy.size.height * 16 / 9, height: proxy.size.height)
                    .position(x: proxy.size.width / 2, y: proxy.size.height / 2)
                    .onAppear() {
                        player.isMuted = true
                        player.play()
                    }
            }
        }
    }
}

It uses the GeometryReader to get the available size to the View, then translates that to a frame for the VideoPlayer. Finally, it positions it so that it's centered using the position modifier.

  • Related