好吧,在做完Demo之后,才发现UIStretch这个组件,这个组件说穿了就是用来控制widget的缩放的。
回想我之前做的Demo,为了让弹出的NGUI对话框变成模式对话框(即它关闭之前,其他UI不能响应),我在UI中嵌入了一层覆盖全屏的透明Sprite,用于捕捉点击事件,这个全屏的我当时是在Sprite上挂了个脚本,在Start的时候,获取Screen的Width和Height,来设置Sprite的长宽像素(而且这样做还是错误的,详见上面那个NGUI屏幕适应的博客),其实用UIStretch的话就完全不用了。
先来看Stretch组件的几个参数和官方解释:
Camera | uiCamera = null |
Camera used to determine the anchor bounds. Set automatically if none was specified. More... |
|
GameObject | container = null |
Object used to determine the container's bounds. Overwrites the camera-based anchoring if the value was specified. More... |
|
Style | style = Style.None |
Stretching style. More... |
|
bool | runOnlyOnce = true |
Whether the operation will occur only once and the script will then be disabled. Screen size changes will still cause the script's logic to execute. More... |
|
Vector2 | relativeSize = Vector2.one |
Relative-to-target size. More... |
|
Vector2 | initialSize = Vector2.one |
The size that the item/image should start out initially. Used for FillKeepingRatio, and FitInternalKeepingRatio. Contributed by Dylan Ryan. More... |
|
Vector2 | borderPadding = Vector2.zero |
Padding applied after the size of the stretched object gets calculated. This value is in pixels. More... |
其中那个Style有这几种类型:
None | |
Horizontal | |
Vertical | |
Both | |
BasedOnHeight | |
FillKeepingRatio | |
FitInternalKeepingRatio |
其中None表示不缩放,Horizontal和Vertical不了解。
前置声明:
mh表示最终我们设计分辨的高。
mw表示最终我们设计分辨率的宽。
sh表示我们屏幕分辨率的高。
sw表示我们屏幕分辨率的宽。
当 mh < sh时,屏幕留黑边。
当mh > sh时,图像有部分超出屏幕外,被截断了。
Both表示长宽分别按照relativeSize设置的X和Y进行缩放。
其中这里的x和y是以屏幕尺寸为单位的,比如x为1,y为1,就表示元素的宽和高变为屏幕的宽高,如下:
mh = sh * y;
mw = sw * x;
BaseOnHeight表示先满足高度的上面的缩放,然后宽的缩放也按高来计算。
mh = sh * y;
mw = sh * x;
FillKeepingRatio
改天再写。
Horizontal为横向拉伸。
Vertical为纵向拉伸。
Both为双向拉伸,但xy方向上的拉伸比例不同。
BasedOnHeight为双向拉伸,但xy方向上的拉伸比例相同,且比例基于height。
FillKeepingRatio为双向拉伸,但xy方向上的拉伸比例相同,比例基于较大者。
FitInternalKeepingRatio为双向拉伸,但xy方向上的比例相同,比例基于较小者。
注意 UIAnchor有个Container标志,如果这个不设置,那么什么Left啊,bottom啊就是相对的整个屏幕而言,如果设置了对象,那就是相对于那个对象来说的。