SwiftUI - To resize the ZStack to the size of the image?

3.9k Views Asked by At

I have a picture and text wrapped in a ZStack and I would like the ZStack to be the shape of the picture but when I put the background in one color, two stripes appear on each side of the picture.
My code :

ZStack {
    Image(schema.image)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .border(Color.white)
        .shadow(color: self.colorShadow ? Color.green : Color.gray.opacity(0.5) ,radius: 10)
    
    ForEach(schema.item) { item in
        Text(String(item.id))
            .font(.headline)
            .foregroundColor(Color.black)
            .padding(5)
            .overlay(
                Circle().stroke(Color.black, lineWidth: 1)
        )
            .position(x: CGFloat(item.coordinatesX), y: CGFloat(item.coordinatesY))
    }
}.background(Color.yellow.opacity(0.5))

Do you have an idea how to trim the ZStack to the size of the image ?

1

There are 1 best solutions below

0
On

ZStack tight to image frame, but due to aspect of image is not 1 then image itself is less (by some side) than own frame.

Use .fill mode

   ZStack {
        Image(schema.image)
            .resizable()
            .aspectRatio(contentMode: .fill)   // << here !!

alternate is to remove ZStack at all, and put Text into overlay of image, like

Image(schema.image)
    .resizable()
    .aspectRatio(contentMode: .fit)
    .border(Color.white)
    .shadow(color: self.colorShadow ? Color.green : Color.gray.opacity(0.5) ,radius: 10)
    .overlay(

      ForEach(schema.item) { item in
        Text(String(item.id))
            .font(.headline)
            .foregroundColor(Color.black)
            .padding(5)
            .overlay(
                Circle().stroke(Color.black, lineWidth: 1)
            )
            .position(x: CGFloat(item.coordinatesX), y: CGFloat(item.coordinatesY))
    })