erotsppa
erotsppa

Reputation: 15071

How to set UIImage's height to always be the same as the width?

struct ContentView: View {
var items: [GridItem] {
    Array(repeating: .init(.adaptive(minimum: 120)), count: 2)
}

private var gridItemLayout = [GridItem(.flexible(), spacing: 20), GridItem(.flexible(), spacing: 20)]

private var colors: [Color] = [.yellow, .purple, .green]

var body: some View {
    NavigationView {
        ScrollView(.vertical, showsIndicators: false) {
            LazyVGrid(columns: gridItemLayout, spacing: 20) {
                ForEach(0 ... 6, id: \.self) {
                    Image(systemName: "plus")
                        .font(.system(size: 30))
                        .frame(maxWidth: .infinity)
                        .background(colors[$0 % colors.count])
                        .cornerRadius(10)
                        .padding(0)
                }
            }
        }.navigationBarTitle(Text("Add Widget"))
            .padding(0)
    }
}

}

Here is an example grid view, the width is automatically managed by the grid parent. And I just want the height to be always the same as the width that way the image is of a square aspect ratio.

Upvotes: 2

Views: 1989

Answers (2)

AntonioWar
AntonioWar

Reputation: 337

If your image is already of a square aspect ratio you can just make it resizable, and select aspectRatio to fit.

Image(systemName: "plus")
     .resizable()
     .aspectRatio(contentMode: .fit)

You can delete .frame(maxWidth: .infinity) because it is intrinsic when you use resizable. This is the effect obtained :

enter image description here

Obviously if your source Images are not squared, you have to specify the aspect ratio that you want.

UPDATE :

If you want a square colored background with a smaller image in the middle you can't do it directly from an Image object like you did in the Example, but you need a more complex object like this :

struct WidgetView : View
{
    var backgroundColor : Color
    var imageName : String
    
    var body : some View
    {
        ZStack {
            Rectangle()
                .fill(backgroundColor)
                .cornerRadius(10)
                .aspectRatio(contentMode: .fit)
            Image(systemName: imageName)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(maxWidth: 50)
                .font(.system(size: 30))
        }
        .padding(5)
    }
}

The usage is very simple :

ForEach(0 ... 6, id: \.self) {
      WidgetView(backgroundColor: colors[$0 % colors.count], imageName: "plus")
}

And the obtained effect is the following :

enter image description here

Upvotes: 2

Charles A.
Charles A.

Reputation: 11143

I would try an aspectRatio modifier with an aspect ratio of 1.0 on your Image. Perhaps just something like .aspectRatio(1.0, contentMode: .fit).

Upvotes: 0

Related Questions