2

My problem is that whenever I change the texture of a sprite, the new texture will retain the size of the original sprite's texture.

I have this code:

mySprite = [CCSprite spriteWithFile:@"mySprite.png"]];

...

// change current stage here 

CCTexture2D *newTexture=[[[CCTexture2D alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"stage number %d.png",currentStageNumber]]]autorelease];

[mySprite setTexture:newTexture];

The new sprite is stretched or compressed depending on the size of the original sprite. If the original sprite is larger, the new texture is stretched.

I didn't have this problem when I was using cocos2d v0.8

What am I doing wrong?

grapefrukt
  • 27,016
  • 6
  • 49
  • 73
marie
  • 101
  • 1
  • 4

2 Answers2

8

Solved:

mySprite = [CCSprite spriteWithFile:@"mySprite.png"]];

...

// change current stage here

CCTexture2D *newTexture=[[[CCTexture2D alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"stage number %d.png",currentStageNumber]]]autorelease];

[mySprite setTexture:newTexture];

[mySprite setTextureRect:CGRectMake(0,0, newTexture.contentSize.width, newTexture.contentSize.height)];

:)

Mutix
  • 4,196
  • 1
  • 27
  • 39
marie
  • 101
  • 1
  • 4
  • The `setTextureRect` call is the magic thing that makes this work. Without it your new texture may be horribly distorted if your sprite has a custom scale-factor applied to it. – aroth Aug 26 '11 at 00:41
0

or:

  CCTexture2D* texture=[[CCTexture2D alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"sky" ofType:@"png"]]  ];
    CCSprite *sprTile=[CCSprite spriteWithTexture:texture];

    [self addChild:sprTile];
    [texture release];
yeahdixon
  • 6,647
  • 1
  • 41
  • 43