NGUI中LabelA停靠LabelB的方法
详情看 http://note.youdao.com/noteshare?id=ec901d56341207052b2d19233b5ddba3
这里仅仅贴出文字,完整内容请看上面链接。
有这样一个需求:让LabelA停靠在LabelB的某个位置,同时要适应labelA的变化的长度。
1. LabelA和LabelB的OverFlow方式是ResizeFreely,使Label的尺寸能够变化。
2. 根据公式得到labelB的位置:
labelB.anchoredposition
= labelA.anchoredposition - labelA.pivot*labelA.size (此时指向labelA的左下角位置)
+ harborAnchor*labelA.size (harborAnchor是归一化的位置值,(1,1)labelA的右上角)
+ AbsoluteOffset(绝对偏移)
3. 需要设置labelB的pivot,例如如果想要让labelB如上图所示停靠在labelA的底线上且是右侧且有一个绝对偏移值(10,0),则将labelB的widget的pivot设置为左下。将harborAnchor设置为(1,0)。
▼代码开始
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UILabelDock: MonoBehaviour
{
public const string Specification = "将某UI停靠在某个Label(称为HarborLabel)的HarborAnchor处,这两个UI需要在同一个GameObject下";
public UILabel m_HarborLabel = null;
[Tooltip("设置港口Widget的锚点,港口Widget内容区域的左下角是(0,0),右上角是(1,1)")]
public Vector2 m_HarborAnchor = new Vector2(1, 0.5f);
RectTransform m_MyRectTransform = null;
RectTransform m_HarborTransform = null;
UIWidget m_HarborWidget = null;
[Tooltip("绝对偏移值")]
public Vector2 m_AbsoluteOffset = new Vector2(0, 0);
private void Awake()
{
m_MyRectTransform = GetComponent<RectTransform>();
m_HarborTransform = m_HarborLabel.GetComponent<RectTransform>();
m_HarborWidget = m_HarborLabel.GetComponent<UIWidget>();
}
public void RefreshDock()
{
Awake();
if (m_HarborLabel == null || m_MyRectTransform == null || m_HarborWidget == null || m_HarborTransform)
{
Debug.LogError("LabelDock Error");
return;
}
//需要确保
m_MyRectTransform.anchorMax = m_HarborTransform.anchorMax;
m_MyRectTransform.anchorMin = m_HarborTransform.anchorMin;
m_MyRectTransform.offsetMax = m_HarborTransform.offsetMax;
m_MyRectTransform.offsetMin = m_HarborTransform.offsetMin;
m_MyRectTransform.pivot = m_HarborTransform.pivot;
m_MyRectTransform.sizeDelta = m_HarborTransform.sizeDelta;
var normalizedOffset = new Vector2(0, 0);
switch (m_HarborWidget.pivot)
{
case UIWidget.Pivot.Bottom:
{
normalizedOffset = new Vector2(0.5f, 0);
break;
}
case UIWidget.Pivot.BottomLeft:
{
normalizedOffset = new Vector2(0, 0);
break;
}
case UIWidget.Pivot.BottomRight:
{
normalizedOffset = new Vector2(1, 0);
break;
}
case UIWidget.Pivot.Center:
{
normalizedOffset = new Vector2(.5f, .5f);
break;
}
case UIWidget.Pivot.Left:
{
normalizedOffset = new Vector2(0, .5f);
break;
}
case UIWidget.Pivot.Right:
{
normalizedOffset = new Vector2(1, .5f);
break;
}
case UIWidget.Pivot.Top:
{
normalizedOffset = new Vector2(.5f, 1);
break;
}
case UIWidget.Pivot.TopLeft:
{
normalizedOffset = new Vector2(0, 1);
break;
}
case UIWidget.Pivot.TopRight:
{
normalizedOffset = new Vector2(1, 1);
break;
}
}
normalizedOffset = m_HarborAnchor - normalizedOffset;
m_MyRectTransform.anchoredPosition = m_HarborTransform.anchoredPosition + new Vector2(normalizedOffset.x * m_HarborLabel.printedSize.x, normalizedOffset.y * m_HarborLabel.printedSize.y) + m_AbsoluteOffset;
}
}
▲代码结束