Clip image to square in SwiftUI

后端 未结 2 835
夕颜
夕颜 2021-02-20 07:57

I am trying to put multiple cells next to each other where each cell consists of an image and a text below. The cell itself should be a square and the image should be scaled to

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 08:33

    It works for me, but I don't know why cornerRadius is necessary...

    import SwiftUI
    
    struct ClippedImage: View {
        let imageName: String
        let width: CGFloat
        let height: CGFloat
    
        init(_ imageName: String, width: CGFloat, height: CGFloat) {
            self.imageName = imageName
            self.width = width
            self.height = height
        }
        var body: some View {
            ZStack {
                Image(imageName)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: width, height: height)
            }
            .cornerRadius(0) // Necessary for working
            .frame(width: width, height: height)
        }
    }
    
    struct ClippedImage_Previews: PreviewProvider {
        static var previews: some View {
            ClippedImage("dishLarge1", width: 100, height: 100)
        }
    }
    

提交回复
热议问题