How to make a LazyVGrid of square images?

Viewed 929

How I can make a square image similar to the photo gallery?

I'm trying the following:

let columns: [GridItem] = [
  GridItem(.flexible()),
  GridItem(.flexible())
]

LazyVGrid(
    columns: columns,
    alignment: .center
) {
    ForEach(self.selectedImages, id: \.self) { image in
        Image(uiImage: image)
            .resizable()
            .scaledToFit()
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
            .aspectRatio(1, contentMode: .fill)
            .background(Color.blue)
    }
}

However, this results in this:

enter image description here

I want to build a 2x2 square grid (similar to this 3x3 below - I want the images to fit nicely into the square)

enter image description here

2 Answers

Try this. It provides the correct aspect ratio and properly clips the images to fill a square:

ForEach(self.selectedImages, id: \.self) { image in
    Color.blue
        .aspectRatio(1, contentMode: .fill)
        .overlay(
            Image(uiImage: image)
                .resizable()
                .scaledToFill()
        ).clipped()
}

I found this to be effective:

Image(uiImage: image)
            .resizable()
            .aspectRatio(1, contentMode: .fill)
            .clipped()

when used with a LazyVGrid and a columns value of

let columns = [GridItem(.adaptive(minimum: 80))]
Related