Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Sprite Kit - SKSpriteNode's .centerRect property not working

I was going through the SpriteKit documentation by Apple and came across a really useful feature that I could use when programming my UI. The problem is I can't get it to work.

Please see this page and scroll down to "Resizing a Sprite" - Apple Docs

I have literally copied the image dimensions and used the same code incase I was doing something wrong. But I always end up with a stretched looking image rather than the correct "end caps" staying the same scale.

I am referring to this code:

SKSpriteNode *button = [SKSpriteNode spriteWithImageNamed:@"stretchable_button.png"];
button.centerRect = CGRectMake(12.0/28.0,12.0/28.0,4.0/28.0,4.0/28.0);

What am I doing wrong? Is there a step I have missed?

EDIT:

Here is the code I have been using. I stripped it of my button class and tried to use it with an SKSPriteNode but still the problem persists. I also changed the image just to make sure it wasnt that. The image im using is a 32x32 at normal size.

SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:@"Button.png"];
[self addChild:button];

button.position = ccp(200, 200);
button.size = CGSizeMake(128, 64);
button.centerRect = CGRectMake(9/32, 9/32, 14/32, 14/32);
like image 564
Tomoso Avatar asked Oct 31 '13 19:10

Tomoso


2 Answers

The .centerRect property works as documented if you adjust the sprites .scale property.

Try:

SKTexture *texture = [SKTexture textureWithImageNamed:@"Button.png"];
SKSpriteNode *button = [[SKSpriteNode alloc] initWithTexture:texture];
button.centerRect = CGRectMake(9/32, 9/32, 14/32, 14/32);
[self addChild:button];    
button.xScale = 128.0/texture.size.width;
button.yScale = 64.0/texture.size.height;
like image 94
rwr Avatar answered Sep 27 '22 22:09

rwr


9/32 is integer division, so the result passed to CGRectMake is zero. Ditto the other three parameters. If you use floating point literals like the example you cite, you might get better results.

like image 30
rickster Avatar answered Sep 27 '22 21:09

rickster