0

I have a simple image detail view, but the problem is either I rotate the image 90 degrees and images taken in landscape mode are properly rotated, but pictures taken in portrait mode aren't. I'd like to read the mode of the image and switch on it if possible?

I also found this answer but am not able to convert an Image back to a UIImage to use it.

import SwiftUI

struct DetailImageView: View {

@Binding var showingSheet: Bool

    var image: Image?

    var body: some View {
        if let unwrappedImage = image {
            unwrappedImage
                .resizable()
                .scaledToFit()
                .edgesIgnoringSafeArea(.all)
                  //.rotationEffect(.degrees(90))
        }
    }
}
GarySabo
  • 5,806
  • 5
  • 49
  • 124
  • 2
    Compare image.size.width to image.size.height? If bigger it’s landscape, if smaller it’s portrait? – Nicholas Rees Feb 03 '21 at 03:15
  • i didn't think of that – GarySabo Feb 03 '21 at 03:17
  • but this is SwiftUI, I thought an `Image` doesn't have a set frame and width height etc. how would I read it? – GarySabo Feb 03 '21 at 03:19
  • Good question. Not sure. I haven’t actually had to get image width or height before. If it doesn’t have built in width and height, you could probably throw a geometry reader around it to pull them out. – Nicholas Rees Feb 03 '21 at 03:20
  • I thought so too, but the GeometryReader is always a parent to the image so before the image is rendered the width and height of the GeometryReader are always the same - the width and height of the available space. – GarySabo Feb 03 '21 at 03:35

1 Answers1

1

I couldn't figure out a way to read any information from an Image so I just decided to pass around the UIImage and then convert to an Image later:

import SwiftUI

struct DetailImageView: View {

@Binding var showingSheet: Bool
    
    var imageAsUIImage: UIImage?
    
    var body: some View {
        
        if let unwrappedImage = imageAsUIImage {
            Image(uiImage:  unwrappedImage)
                .resizable()
                .scaledToFit()
                .padding()
                .if((imageAsUIImage?.size.width ?? 100) > (imageAsUIImage?.size.height ?? 100)) { $0.rotationEffect(Angle.degrees(90)) }
        }
        
    }
}
GarySabo
  • 5,806
  • 5
  • 49
  • 124