我正在尝试通过 SwiftUI 中的 clipShape 从图像创建 Sprite 。我的代码并没有按照我想要的方式工作。剪裁的图像相对于从中剪裁的图像定位。例如,假设我们有一个 super 马里奥 Sprite 表。这张纸上有马里奥和路易吉的镜框,马里奥的镜框在上面。
当我使用 clipShape 并尝试将 Mario 和 Luigi 定位在起点时,Mario 的起点总是比 Luigi 高,因为他的帧在源图像上更高。我需要他们的图像在剪辑后从同一位置开始。
//Mario starting at the first frame, top left
Image("sprites")
.clipShape(Rectangle().path(in: CGRect(x: 0, y:0, width: 50, height: 100)))
.frame(width: 50, height: 100)
.position(x: 0, y: 0)
//Luigi - start frame is 100 pixels under Mario's
Image("sprites")
.clipShape(Rectangle().path(in: CGRect(x: 0, y:100, width: 50, height: 100)))
.frame(width: 50, height: 100)
.position(x: 0, y: 0)
有什么想法吗?
最佳答案
ImagePaint
应该满足您的需求,如下所示(假设每个图像 50x200 有两个高度相等的 Sprite )
注意:sourceRect 在 [0:1] 范围内
// Mario (upper half of image)
Rectangle().fill(ImagePaint(image: Image("sprites"), sourceRect: CGRect(x: 0, y:0, width: 1, height: 0.5), scale: 1))
.frame(width: 50, height: 100)
// Luigi (lower half of image)
Rectangle().fill(ImagePaint(image: Image("sprites"), sourceRect: CGRect(x: 0, y:0.5, width: 1, height: 1), scale: 1))
.frame(width: 50, height: 100)
关于ios - Swift 中的剪辑形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61548880/