Node* node1 = Node::create();
Node* node2 = Node::create();
node2->addChild(Sprite::create(“1.png”));
node1->addChild(node2);
node1->getBoundingBox();
这时node1的BoudingBox宽高为0, 如何能获取到包含它所有子元素的BoudingBox?
Node* node1 = Node::create();
Node* node2 = Node::create();
node2->addChild(Sprite::create(“1.png”));
node1->addChild(node2);
node1->getBoundingBox();
这时node1的BoudingBox宽高为0, 如何能获取到包含它所有子元素的BoudingBox?
貌似没人关注这问题。。。
自己写了2个函数,递归获取Node的BoundingBox和ContentSize,用着貌似没什么Bug。。。 onlyTexture参数的意思是只统计贴图占用的空间
Rect getBoundingBoxRecursive(Node *node, bool onlyTexture = true) {
CCAssert(node != nullptr, "node can't be null");
Rect nodeRect = node->getBoundingBox();
nodeRect.origin = node->convertToWorldSpace(Vec2::ZERO);
for_each(node->getChildren().begin(), node->getChildren().end(), &](Node* subNode) {
Rect subNodeRect;
subNodeRect = getBoundingBoxRecursive(subNode);
if (onlyTexture && nodeRect.size.equals(Size::ZERO)) {
nodeRect.origin = subNodeRect.origin;
}
nodeRect.merge(subNodeRect);
});
return nodeRect;
}
Vec2 getContentSizeRecursive(Node *node, bool onlyTexture = true) {
return getBoundingBoxRecursive(node, onlyTexture).size;
}
```
顺便说一下,获取的BoundingBox是世界坐标系下的,需要自己转到需要的Node坐标系下面
CCRect CCArmature::boundingBox()
{
float minx, miny, maxx, maxy = 0;
bool first = true;
CCRect boundingBox = CCRectMake(0, 0, 0, 0);
CCObject *object = NULL;
CCARRAY_FOREACH(m_pChildren, object)
{
if (CCBone *bone = dynamic_cast(object))
{
CCRect r = bone->getDisplayManager()->getBoundingBox();
if (r.size.width == 0 || r.size.height == 0)
continue;
if(first)
{
minx = r.getMinX();
miny = r.getMinY();
maxx = r.getMaxX();
maxy = r.getMaxY();
first = false;
}
else
{
minx = r.getMinX() < boundingBox.getMinX() ? r.getMinX() : boundingBox.getMinX();
miny = r.getMinY() < boundingBox.getMinY() ? r.getMinY() : boundingBox.getMinY();
maxx = r.getMaxX() > boundingBox.getMaxX() ? r.getMaxX() : boundingBox.getMaxX();
maxy = r.getMaxY() > boundingBox.getMaxY() ? r.getMaxY() : boundingBox.getMaxY();
}
boundingBox.setRect(minx, miny, maxx - minx, maxy - miny);
}
}
return CCRectApplyAffineTransform(boundingBox, nodeToParentTransform());
}
```
从CCArmature直接偷来的代码。
递归什么的,我脑子可能没长那根弦真的好难懂。。
boundingbox 需要被加到场景上之后才能获取!,因为坐标是世界坐标,不放到场景上哪来的世界坐标