Asset catalog image slicing in Spritekit

1k views Asked by At

I want to make my button horizontaly and vertically stretchable.

In the storyboard everything is okay

storyboard image

But in SpriteKit is not the same!

I'am loading the image using

let spriteTexture = SKTexture(imageNamed: "button");
let sprite = SKSpriteNode(texture: spriteTexture, color: nil, size: CGSizeMake(290, 400));

spritekit image

2

There are 2 answers

0
grape1 On BEST ANSWER

If centeRect, yScale, xScale are set the button will streach properly

let sprite = SKSpriteNode(texture: spriteTexture, color: nil, size: CGSizeMake(290, 58));
sprite.position = CGPointMake(0, -100);
sprite.centerRect = CGRectMake( 140/290.0, 24/58.0, 10.0/58.0, 10.0/58.0);
sprite.yScale = CGFloat(250.0 / 58.0);
sprite.xScale = CGFloat((self.frame.size.width - 20) / 290.0);

self.addChild(sprite);
1
Andy Heard On

You need to set your sprite's centreRect property that defines how it is scaled. This is a normalised CGRect in the centre that will not be scaled but the elements around it will be.

Looking at your button you want everything but the centre few pixels to remain unstretched. To set the centreRect property:

sprite.centerRect = CGRectMake(0.49, 0.49, 0.02, 0.02)

This means that a rectangle is drawn from a point 49% of the width and height away from the corner of the sprite and has sides of length 2% of the sprites width and height respectively. Therefore only the centre 2% of the texture is stretched.

This is discussed in the "Working with Sprites" document that Apple provides and explains it far more effectively that I just did under the section "Resizing a Sprite":

https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Sprites/Sprites.html