using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("NGUI/MyExtensions/Panel Stretch")]
public class UIPanelStretch : MonoBehaviour
{
public enum Style
{
None,
Horizontal,
Vertical,
Both,
BasedOnHeight,
}
public Camera uiCamera = null;
public UIWidget widgetContainer = null;
public UIPanel panelContainer = null;
public Style style = Style.None;
public Vector2 relativeSize = Vector2.one;
UIRoot mRoot;
UIPanel mPanel; // The panel on the object which we'll be manipulating
void Awake ()
{
// Get the panel
mPanel = GetComponent<UIPanel>();
}
void Start ()
{
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
mRoot = NGUITools.FindInParents<UIRoot>(gameObject);
}
void Update ()
{
if(mPanel == null) return;
if (style != Style.None)
{
if (panelContainer != null)
{
if (panelContainer.clipping == UIDrawCall.Clipping.None)
{
// Panel has no clipping -- just use the screen's dimensions
rect.xMin = -Screen.width * 0.5f;
rect.yMin = -Screen.height * 0.5f;
rect.xMax = -rect.xMin;
rect.yMax = -rect.yMin;
}
else
{
// Panel has clipping -- use it as the rect
Vector4 pos = panelContainer.clipRange;
rect.x = pos.x - (pos.z * 0.5f);
rect.y = pos.y - (pos.w * 0.5f);
rect.width = pos.z;
rect.height = pos.w;
}
}
else if (widgetContainer != null)
{
// Widget is used -- use its bounds as the container's bounds
Transform t = widgetContainer.cachedTransform;
Vector3 ls = t.localScale;
Vector3 lp = t.localPosition;
Vector3 size = widgetContainer.relativeSize;
Vector3 offset = widgetContainer.pivotOffset;
offset.y -= 1f;
offset.x *= (widgetContainer.relativeSize.x * ls.x);
offset.y *= (widgetContainer.relativeSize.y * ls.y);
rect.x = lp.x + offset.x;
rect.y = lp.y + offset.y;
rect.width = size.x * ls.x;
rect.height = size.y * ls.y;
}
else if (uiCamera != null)
{
rect = uiCamera.pixelRect;
}
else return;
float rectWidth = rect.width;
float rectHeight = rect.height;
float adj = (mRoot != null) ? mRoot.pixelSizeAdjustment : 1f;
if (adj != 1f && rectHeight > 1f)
{
float scale = mRoot.activeHeight / rectHeight;
rectWidth *= scale;
rectHeight *= scale;
}
// In this version we're adjusting the clip range, not the transform.
Vector4 clipRange = mPanel.clipRange;
// z = width
// w = height
if (style == Style.BasedOnHeight)
{
clipRange.z = relativeSize.x * rectHeight;
clipRange.w = relativeSize.y * rectHeight;
}
else
{
if (style == Style.Both || style == Style.Horizontal) clipRange.z = relativeSize.x * rectWidth;
if (style == Style.Both || style == Style.Vertical) clipRange.w = relativeSize.y * rectHeight;
}
mPanel.clipRange = clipRange;
}
}
}