30

That's the question xD

Given an instance of a CCSprite in cocos2d in iphone, what method can I use to obtain the image width and height?

Mxyk
  • 10,678
  • 16
  • 57
  • 76
Manuel Araoz
  • 15,962
  • 24
  • 71
  • 95

5 Answers5

54

The CCSprite class has a bounding box property that's a CGRect:

  CCSprite *sprite = [CCSprite spriteWithFile: @"file.png"];
  int width = [sprite boundingBox].size.width;

I added a width and height methods to my CCSprite subclass.

-(CGFloat) width
{
    return [self boundingBox].size.width;
}

-(CGFloat) height
{
    return [self boundingBox].size.height;
}
robterrell
  • 756
  • 7
  • 5
39

raw width:
sprite.contentSize.width

raw height:
sprite.contentSize.height

current width: sprite.contentSize.width * sprite.scaleX

current height: sprite.contentSize.height * sprite.scaleY

Roopesh Shenoy
  • 3,389
  • 1
  • 33
  • 50
yubenyi
  • 620
  • 5
  • 10
0

IN cocos2d-x

sprite->boundingBox().size.width;

sprite->boundingBox().size.height;
Singhak
  • 8,508
  • 2
  • 31
  • 34
0

In cocos2d-x v3.x, boundingBox is deprecated in the Node class (i.e. the super class of Sprite). Use the following code instead:

auto spriteWidth = sprite->getTextureRect().size.width;
auto spriteHeight = sprite->getTextureRect().size.height;

or

auto spriteWidth = sprite->getContentSize().width;
auto spriteHeight = sprite->getContentSize().height;
GaloisPlusPlus
  • 403
  • 4
  • 20
0

Answer for 2018 (Cocos2d-x v3.x:)

The other answers are incomplete and out-of-date.

Note that I'm using JavaScript below along with destructuring assignment syntax. Be sure to view the Cocos API documentation for your language implementation.


getBoundingBox()

Gives you the:

  • Scaled size (the size after setScale() is applied to the sprite).
  • Coordinates of sprite on the screen. Note that the default anchorPoint for sprites is (0.5, 0.5), while this coordinate represents the (0, 0) position. In other words, if the anchorPoint is set at the default, then getBoundingBox().x + getBoundingBox().width / 2 = getPosition().x (the x value you set in setPosition()).

Example:

const boundingBox = sprite.getBoundingBox();
const { x, y, width, height } = boundingBox;

getContentSize()

Gives you the:

  • Unscaled size.

Example:

const contentSize = sprite.getContentSize();
const { x, y } = contentSize;

getTextureRect()

Gives you the:

  • Unscaled size.
  • Coordinates of sprite on the texture from which it is extracted (i.e. sprite sheet)

Example:

const textureRect = sprite.getTextureRect();
const { x, y, width, height } = textureRect;
jabacchetta
  • 45,013
  • 9
  • 63
  • 75