cocos2dx_实例分析getBoundingBox和getContentSize

1:分析BoundingBox.
首先来看这样一段代码,其中HelloWorld的图片大小为195*270

Node* pNode = Node::create();
addChild(pNode);
Sprite* pSprite1 = Sprite::create("HelloWorld.png");
pNode->addChild(pSprite1);

Rect rt1 = pSprite1->getBoundingBox();
pSprite1->setPosition(10, 10);
Rect rt2 = pSprite1->getBoundingBox();

pSprite1->setPosition(Vec2::ZERO);
pSprite1->setScale(2);
Rect rt3 = pSprite1->getBoundingBox();

Rect rt4 = pNode->getBoundingBox();

Sprite* pSprite2 = Sprite::create("HelloWorld.png");
pNode->addChild(pSprite2);
pSprite2->setPosition(100, 0);

pNode->setPosition(10, 10);
Rect rt5 = pNode->getBoundingBox();

运行结果:
rt1 (-97.5, -135, 195, 270)
rt2 (-87.5, -125, 195, 270)
rt3 (-190, -270, 390, 540)
rt4 (0, 0, 0, 0)
rt5 (10, 10, 0, 0)
可以发现一个节点boundingBox和节点在父节点中的位置以及scale都有关系,来看下源码。
Rect Node::getBoundingBox() const
{
Rect rect(0, 0, _contentSize.width, _contentSize.height);
return RectApplyAffineTransform(rect, getNodeToParentAffineTransform());
}
AffineTransform 类表示 2D 仿射变换,它执行从 2D 坐标到其他 2D 坐标的线性映射。左乘该矩阵能将子节点坐标系转换到父节点坐标系中。子节点的平移缩放反转等操作都会记录在这个矩阵中。
boundingbox中的origin表示子节点在父节点坐标中的左下角,Size表示内容大小。
一个节点的boundingBox和它的子节点没关系,因为它是从contentSize转换过去的。
2:分析下ContentSize
这是node中关于contentSize的两个函数
const Size& Node::getContentSize() const
{
return _contentSize;
}
void Node::setContentSize(const Size & size)
{
if (! size.equals(_contentSize))
{
_contentSize = size;
_anchorPointInPoints.set(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
_transformUpdated = _transformDirty = _inverseDirty = _contentSizeDirty = true;
}
}
可以发现改变contentsize会改变锚点的空间位置并且重绘节点。

Node* pNode = Node::create();
addChild(pNode);
Sprite* pSprite1 = Sprite::create("HelloWorld.png");
pNode->addChild(pSprite1);
Size sz1 = pSprite1->getContentSize();
pSprite1->setScale(2);
Size sz2 = pSprite1->getContentSize();
pSprite1->setPosition(100, 100);
Size sz3 = pSprite1->getContentSize();
pSprite1->setFlippedX(true);
Size sz4 = pSprite1->getContentSize();
pSprite1->setTextureRect(Rect(50, 50, 100, 100));
Size sz5 = pSprite1->getContentSize();

运行代码发现 sz1-4的值都为 (195, 270),sz5为(100, 100)
Sprite的contentSize为显示大小。
可以去看下CCSprite的这个函数
virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize);

总结下:contentSize表示内容的大小,是在节点坐标系内的度量。BoundingBox是包围盒的区域,是在父节点中的度量。
bool isTouchInsideNode(Touch* pTouch, Node* pNode)
{
//1
return pNode->getBoundingBox().containsPoint(pNode->getParent()->convertTouchToNodeSpace(pTouch));
//2
Size sz = pNode->getContentSize();
Rect rt = (0, 0, sz.width, sz.height);
return rt.containsPoint(pNode->convertTouchToNodeSpace(pTouch));
}
可以自行感受下这两个的区别。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值