CYAD
CYAD

Reputation: 1277

clipShape in Swift

I'm trying to create sprites from an image via clipShape in SwiftUI. My code isn't quite working the way I'd like. The clipped image is positioned relative to the image it is clipped from. For example, let's say we had a Super Mario sprite sheet. On the sheet are frames for both Mario and Luigi, with Mario's frames on top.

When I use clipShape and try to position Mario and Luigi at the starting point, Mario always starts higher than Luigi since his his frames are higher on the source image. I need their images to start at the same position once clipped.

//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)

Any thoughts?

Upvotes: 1

Views: 680

Answers (1)

Asperi
Asperi

Reputation: 257729

The ImagePaint should fit your needs, like below (assuming you have two sprites per image 50x200 with equal heights)

Note: sourceRect is in [0:1] range

// 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)

Upvotes: 1

Related Questions