Search code examples
swiftimageswiftui

How to split an image in multiple parts in SwiftUI


I try to build a simple puzzle game with SwiftUI. There is a square image, let's say 300 * 300. I want to either split it into nine 100 * 100 images or show 100 * 100 parts of the original image.

clipped() modifier afaik only allows to cut parts of the image but not to select for example the middle part of the original image. Anyone with a hint how to start there?


Solution

  • You could use .offset to move the image into position before applying a frame and a clip shape. Something like:

    VStack {
        ForEach(0..<3, id: \.self) { row in
            HStack {
                ForEach(0..<3, id: \.self) { col in
                    theImage
                        .offset(x: CGFloat(-100 * col), y: CGFloat(-100 * row))
                        .frame(width: 100, height: 100, alignment: .topLeading)
                        .clipShape(Rectangle())
                }
            }
        }
    }
    

    For example, using this image:

    private var theImage: some View {
        Image(systemName: "tortoise")
            .resizable()
            .scaledToFit()
            .padding(20)
            .frame(width: 300, height: 300)
            .background(.yellow)
    }
    

    Screenshot