【问题标题】:clipShape in SwiftSwift 中的剪辑形状
【发布时间】:2020-05-02 03:57:51
【问题描述】:

我正在尝试通过 SwiftUI 中的 clipShape 从图像创建精灵。我的代码并没有按照我想要的方式工作。剪裁的图像相对于从中剪裁的图像定位。例如,假设我们有一个超级马里奥精灵表。这张纸上有马里奥和路易吉的镜框,上面是马里奥的镜框。

当我使用 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)

有什么想法吗?

【问题讨论】:

  • .clipShape 不会裁剪(或剪切)图像,也不会改变布局......它只会使指定的部分可见和其他透明,所以我认为它不是你的好工具目的。最好在 之前 在 Photoshop 之类的工具中剪切这些精灵,然后按原样使用。
  • 谢谢。你知道是否有另一种方法可以实现我想要做的事情?

标签: ios image swiftui


【解决方案1】:

ImagePaint 应该满足您的需求,如下所示(假设您在每张 50x200 的图像中有两个高度相同的精灵)

注意: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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多