Home > Blockchain >  How to properly fit a filled Image in its bounds on SwiftUI?
How to properly fit a filled Image in its bounds on SwiftUI?

Time:05-10

I have to fix a problem with Images on SwiftUI. I currently have to fill the images I receive in a certain vertical container, which are the cells of a LazyVGrid, but the problem is that the tappable area expands over the designated one.

I used the Accessibility Inspector, and I found out that the area in excess is due the Images. (screenshot attached)

The code I'm using is something similar to the following:

Image(uiImage: image.image)
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(
        maxWidth: width,
        maxHeight: height
    )
    .clipped()

I thought that by having the frames and the clipped method I could get rid of this problem, but that's not the case unless I'm using some squared images. Any idea of what could work to fix this problem? Thanks!

enter image description here

CodePudding user response:

Just add .contentShape(Rectangle()) at the bottom:

            Image(uiImage: image.image)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(
                    maxWidth: width,
                    maxHeight: height
                )
                .clipped()
                .contentShape(Rectangle())    // <- Here!

CodePudding user response:

Wrap content in Geometry Reader and you need to know the aspect ratio like I set 720/460 below

GeometryReader { gr in
       Image(uiImage: image.image)
            .resizable()
             .aspectRatio(720/460, contentMode: .fit)
          }
        .clipped()
        .aspectRatio(720/460, contentMode: .fit)
  • Related