如何在 SwiftUI 中将图像分割成多个部分

问题描述 投票:0回答:1

我尝试使用 SwiftUI 构建一个简单的益智游戏。 有一个正方形图像,假设为 300 * 300。我想将其分成九个 100 * 100 图像或显示原始图像的 100 * 100 部分。

clipped()
修改器据我所知仅允许剪切图像的部分内容,但不允许选择例如原始图像的中间部分。 有人提示如何从这里开始吗?

swift image swiftui
1个回答
1
投票

在应用框架和剪辑形状之前,您可以使用

.offset
将图像移动到位。比如:

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())
            }
        }
    }
}

例如,使用此图像:

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

Screenshot

© www.soinside.com 2019 - 2024. All rights reserved.