I am using UIImagePickerController to capture a photo from the camera or select from the photo library, and then display the image. This works fine for landscape/horizontal oriented photos, but photos in portrait/vertical orientation are showing up stretched out horizontally.
I've tried .scaledToFit() and .aspectRatio(contentMode: .fit), but it still shows up stretched. Any help is very much appreciated.
Code to display image:
struct AddNewItem: View {
@State private var showImagePicker: Bool = true
@State private var image: UIImage = nil
@State var showCamera: Bool = false
@State private var showImageEditor: Bool = false
var body: some View {
VStack {
Image(uiImage: image ?? UIImage(named: "placeholder")!)
.resizable()
.scaledToFit()
.aspectRatio(contentMode: .fit)
}
//Show the photo capture view
.sheet(isPresented: self.$showImagePicker) {
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image, showImageEditor: self.$showImageEditor, showCamera: self.$showCamera)
}
}
}
Image Picker Coordinator:
class ImagePickerCoordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@Binding var isShown: Bool
@Binding var image: UIImage?
@Binding var showEditor: Bool
init(isShown: Binding<Bool>, image: Binding<UIImage?>, showEditor: Binding<Bool>) {
_isShown = isShown
_image = image
_showEditor = showEditor
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
image = uiImage
isShown = false
showEditor = true
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
isShown = false
}
}
Image Picker:
struct ImagePicker: UIViewControllerRepresentable {
@Binding var pickerIsShown: Bool
@Binding var image: UIImage?
@Binding var showImageEditor: Bool
@Binding var showCamera: Bool
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
func makeCoordinator() -> ImagePickerCoordinator {
return ImagePickerCoordinator(isShown: $pickerIsShown, image: $image, showEditor: $showImageEditor)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
if showCamera {
picker.sourceType = .camera
} else {
picker.sourceType = .photoLibrary
}
picker.delegate = context.coordinator
return picker
}
}
Photo Capture View:
struct PhotoCaptureView: View {
@Binding var showImagePicker: Bool
@Binding var image: UIImage?
@Binding var showImageEditor: Bool
@Binding var showCamera: Bool
var body: some View {
ImagePicker(pickerIsShown: $showImagePicker, image: $image, showImageEditor: $showImageEditor, showCamera: $showCamera)
}
}