-3

In this code, the items in the grid is displayed as square, but the image is squished. Some of these images are rectangular shape, I want to crop it into a square to fit into this grid.

struct GalleryView: View {
    @State private var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9].shuffled()

    let columns = [
        GridItem(.adaptive(minimum: 100, maximum: 1000)),
        GridItem(.adaptive(minimum: 100, maximum: 1000))
    ]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(arr, id: \.self) { id in
                    Image("test\(id)")
                        .resizable()
                        .aspectRatio(1, contentMode: .fit)
                        .clipShape(Rectangle())   //this has 0 effect
                        .cornerRadius(20)
                        .listRowSeparator(.hidden)
                }
            }
            .padding(.horizontal)
        }
    }
}

Note that the challenge is to not set a custom size for the cell but let it take as much space as needed in the grid while maintaining the square aspect ration and crop.

erotsppa
  • 14,248
  • 33
  • 123
  • 181

1 Answers1

0

The answer seems to be:

Color.blue
                        .aspectRatio(1, contentMode: .fill)
                        .overlay(
                            Image("test\(id)")
                                .resizable()
                                .scaledToFill()
                        )
                        .clipped()
erotsppa
  • 14,248
  • 33
  • 123
  • 181