哎,这个BUG从版本3.0,一直到3.3final。 为何还不修复?
cocostudio UI编辑器里,控件在父容器里的坐标会受锚点影响。
比如一个400x400的容器,我们把锚点定在中心(200,200)
然后我在容器中心点位置放一个按钮,那么该按钮在编辑器里的坐标为(0,0),而在程序里正确的坐标应该为(200,200)。
也就是说编辑器里,控件在容器里的坐标值是根据容器锚点(200,200)来设置的,而程序中控件是按照容器的左下角(0,0)设置坐标的的,这个是导致UI错位的真正原因。
以前有个偷懒的办法,调用容器的ignoreAnchorPointForPosition(true)这个函数来解决,但是这个办法治标不治本,当我调用上面的函数后,发现容器的锚点变为(0,0)了,容器跑别地方去了 。。。
目前我的解决办法,编辑器里使用绝对布局设置坐标,然后调用下面的这段函数,强制矫正锚点带来的问题。
看不清代码的看我这篇笔记: http://note.youdao.com/share/?id=2a7b04516ae4db11b29dfbf6e006569f&type=note,1
static void adjustLayoutPostion(cocos2d::Node* parent)
{
if (dynamic_cast<cocos2d::ui::Layout*>(parent)) {
for (auto child:parent->getChildren()) {
auto papoint = parent->getAnchorPoint();
auto psize = parent->getContentSize();
auto cpos = child->getPosition();
cpos.x += psize.width * papoint.x;
cpos.y += psize.height * papoint.y;
child->setPosition(cpos);
adjustLayoutPostion(child);
}
}
}