4

How can I create a CCSprite that scales the image to fit within input bounds, i.e. if I want a CCSprite that is width = 70 and height = 50 and scales the image in the file to 70,50. Is there a simple way to do this other than compute the scale factor from the image's size in comparison to the desired final size?

Joey
  • 7,537
  • 12
  • 52
  • 104

2 Answers2

9

Here is a category implementation that works, based on the answer from @Martin

@implementation CCSprite(Resize)

-(void)resizeTo:(CGSize) theSize
{
    CGFloat newWidth = theSize.width;
    CGFloat newHeight = theSize.height;


    float startWidth = self.contentSize.width;
    float startHeight = self.contentSize.height;

    float newScaleX = newWidth/startWidth;
    float newScaleY = newHeight/startHeight;

    self.scaleX = newScaleX;
    self.scaleY = newScaleY;

}

@end
Michael Behan
  • 3,433
  • 2
  • 28
  • 38
3

Not sure if there's an easier way but I'd just do something like

            CGFloat myDesiredWidth=50;
        CGFloat myDesiredHeight=70;

        CGFloat startWidth=mySprite.size.width;
        CGFloat startHeight=mySprite.size.height;

        CGFloat scaleX=myDesiredWidth/startWidth;
        CGFloat scaleY=myDesiredHeight/startHeight;

        CGFloat finalScale=MIN(scaleX,scaleY);
        mySprite.scale=finalScale;

Drop that into a category on CCSprite and you'll never have to worry about it again

Martin
  • 1,570
  • 3
  • 19
  • 32