iosswiftuiuiviewrepresentablephlivephoto

SwiftUI: how to resize the UIViewRepresentable output?


I try to build a basic Live Photo app on SwiftUI and struggle with display of the selected photo. To do so I tried to make UIViewRepresentable for PHLivePhotoView:

import SwiftUI
import PhotosUI

struct LivePhotoView: UIViewRepresentable {
    @Binding var livephoto: PHLivePhoto

    func makeUIView(context: Context) -> PHLivePhotoView {
        return PHLivePhotoView()
    }

    func updateUIView(_ lpView: PHLivePhotoView, context: Context) {
        lpView.livePhoto = livephoto
    }
}

In my Main view I call it like that:

if pickerResult.count > 0 {
    LivePhotoView(livephoto: $pickerResult[0])
}

It works fine up to the moment when I try to restrict the view size. I want to put the preview into a square box with something like that

LivePhotoView(livephoto: $pickerResult[0])
    .scaledToFit()
    .frame(width: geo.size.width, height: geo.size.width, alignment: .center)

but scaledToFit() doesn't seem to work, all I have is a cropped image. Expected behaviour is to have an image with preserved aspect ratio and an empty space on a shorter side. Is this even possible?


Solution

  • Do it on original view and in SwiftUI only limit a frame, like

    func makeUIView(context: Context) -> PHLivePhotoView {
        let photoView = PHLivePhotoView()
        photoView.contentMode = .scaleAspectFit
        return photoView
    }
    

    and (or even w/o) frame modifier

    LivePhotoView(livephoto: $pickerResult[0])
        .frame(width: geo.size.width, height: geo.size.width, alignment: .center)