40
votes

I want to resize an Image frame to be a square that takes the same width of the iPhone's screen and consequently the same value (screen width) for height.

The following code don't work cause it gives the image the same height of the view.

var body: some View {
        Image("someImage")
            .resizable()
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .clipped()
    }
4
It sounds like you have a different issue, because you are working with Image. (And yes, there are two fairly simple ways to get the screen width, but I don't think they will solve your problem.) Have you tried adding this modifier? .aspectRatio(contentMode: .fit) - dfd
Second comment... I upvoted the answer by @DoesData because it's one to two SwiftUI ways of doing this (and didn't downvote the answer from @MehmetAliVataniar even though it makes some serious non-SwiftUI assumptions. The second way - found in the following question, uses subclassing UIHostingController and may get you much more things you can do: stackoverflow.com/questions/57441654/… - dfd

4 Answers

56
votes

You can create a UIScreen extension for the same. Like:

extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}

Usage:

UIScreen.screenWidth
35
votes

Try using Geometry Reader

let placeholder = UIImage(systemName: "photo")! // SF Symbols

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            Image(uiImage: placeholder) 
            .resizable()
            .frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
            // .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .clipped()
        }
    }
}

enter image description here

15
votes

You can use UIScreen.main.bounds .width or .height

.frame(
   width:UIScreen.main.bounds.width,
   height:UIScreen.main.bounds.height
)
5
votes

The simplest way would be to make the image resizable and set the aspect ratio to 1.0:

var body: some View {
    Image("someImage")
       .resizable()
       .aspectRatio(1.0, contentMode: .fit)
}