ios - Swift 中的剪辑形状

标签 ios image swiftui

我正在尝试通过 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/

相关文章:

SwiftUI List onDelete Index 设置为 int

ios - 从 imagePickerController 选择照片后如何更改标题单元格中的 imageView?

ios - UIAlertController 未从 AppDelegate 显示

python - 如何移除移动物体以仅获取背景?

html - 指定图像尺寸以提高站点速度

swiftui - 有没有办法在 SwiftUI 中检测 `BarMark` 上的悬停手势?

iphone - TBXML textForElement 不解析一个元素

iOS:为什么带有 setCornerRadius 的 UITextField 会截断文本

c++ - CImg : Image binarization result fails

SwiftUI - 使用不同曲线为多个参数设置动画