【问题标题】:how to obtain a CCSprite's width and height in cocos2d for iphone如何在 cocos2d for iphone 中获取 CCSprite 的宽度和高度
【发布时间】:2011-01-31 00:38:33
【问题描述】:

这就是问题xD

给定一个iphone中cocos2d中CCSprite的实例,我可以用什么方法来获取图片的宽高?

【问题讨论】:

    标签: iphone sprite dimensions ccsprite


    【解决方案1】:

    CCSprite 类有一个边界框属性,它是一个 CGRect:

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

    我为我的 CCSprite 子类添加了宽度和高度方法。

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

    【讨论】:

      【解决方案2】:

      原始宽度:
      sprite.contentSize.width

      原始高度:
      sprite.contentSize.height

      当前宽度: sprite.contentSize.width * sprite.scaleX

      当前高度: sprite.contentSize.height * sprite.scaleY

      【讨论】:

      • 这应该是正确的接受答案,即使 robterrell 的答案也给出了正确的值。不过这个更好。
      • 第一个有大小写错误,是sprite.contentSize.width而不是sprite.contentsize.width
      • contentSize 是否考虑轮换?
      【解决方案3】:

      在 cocos2d-x 中

      sprite->boundingBox().size.width;
      
      sprite->boundingBox().size.height;
      

      【讨论】:

        【解决方案4】:

        在 cocos2d-x v3.x 中,boundingBoxNode 类(即 Sprite 的超类)中已被弃用。请改用以下代码:

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

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

        【讨论】:

          【解决方案5】:

          2018 年的答案(Cocos2d-x v3.x:)

          其他答案不完整且已过时。

          请注意,我在下面使用 JavaScript 和 destructuring assignment syntax。请务必查看 Cocos API documentation 以了解您的语言实现。


          getBoundingBox()

          为您提供:

          • 缩放大小(setScale() 之后的大小应用于精灵)。
          • 屏幕上精灵的坐标。请注意,精灵的默认 anchorPoint 是 (0.5, 0.5),而此坐标表示 (0, 0) 位置。也就是说,如果anchorPoint设置为默认值,那么getBoundingBox().x + getBoundingBox().width / 2 = getPosition().x(你在setPosition()中设置的x值)。

          例子:

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

          getContentSize()

          为您提供:

          • 未缩放的大小。

          例子:

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

          getTextureRect()

          为您提供:

          • 未缩放的大小。
          • 精灵在从中提取的纹理(即精灵表)上的坐标

          例子:

          const textureRect = sprite.getTextureRect();
          const { x, y, width, height } = textureRect;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-07-12
            • 2014-05-01
            • 2011-08-13
            • 1970-01-01
            • 1970-01-01
            • 2019-12-26
            • 2011-09-25
            相关资源
            最近更新 更多