Joey
Joey

Reputation: 7527

How do I create a CCSprite to set bounds?

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?

Upvotes: 4

Views: 5123

Answers (2)

Michael Behan
Michael Behan

Reputation: 3443

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

Upvotes: 9

Martin
Martin

Reputation: 1640

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

Upvotes: 3

Related Questions