昨天发现自己做的时间段选择UI不能自适应。任何不能做自适应的插件都是不合格的。所以就在找原因。后来发现是在doubleslider代码中的错误。之前的代码版本是在Awake里获取width。后来设置锚点后打印width接近0.这是明显的错误。翻unityanswer发现确实有人遇到这个问题,是因为Awake初始化ui的Rectangle还没有初始化出来,所以获取到的值是错误的,要在Start函数或者其他的函数都可以。原文地址:时间段选择博客。
下面说下rectTransform.rect.size和rectTransform.sizeDelta的区别:
rect.size获取到的就是UI元素的长度和高度。不管你怎么设置锚点。
而rectTransform.sizeDelta在官网资料的表述为:
-
If the anchors are together, sizeDelta
is the same
as size. If the anchors are
in each of
-
the four corners of the parent,the sizeDelta
is how much bigger or smaller the rectangle
is
-
compared to its parent.
说的和没说一样。后来查资料发现是这样的:当四个锚点在同一个位置的时候,sizeDelta和rect.size是一样大小的。而当四个锚点分散开来。则:
sizeDelta.x=rect.x-anchorRectangle.x; sizeDelta.y=rect.y-anchorRectangle.y;
所以就可以理解为什么四个锚点在同一位置时,sizeDelta和rect.size是一样大小的。