好吧,写了那么多年Unity,
发现自己还是什么都不会
参考:
自动生成代码(前)
Unity UI代码自动生成 - 盘子脸 - 博客园 (cnblogs.com)
UI动画
Unity进阶技巧 - 动态创建UGUI - 简书 (jianshu.com)
UI边界Bounds
假如有1个UI
下面有2个UIImage
是可以计算子节点的区域大小的
只要在第一个UI节点添加脚本,
[ExecuteInEditMode]
public class BoundsManager : MonoBehaviour
{
GameObject _tempObject;
private Canvas _canvas;
void OnEnable()
{
if(_tempObject==null)
{
_tempObject = new GameObject("TEMP");
_tempObject.AddComponent<Image>();
}
var rect = transform.GetComponent<RectTransform>();
_canvas = rect.GetComponentInParent<Canvas>();
_tempObject.transform.SetParent(_canvas.transform,false);
//uNITY 提供的关键方法
var bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(_canvas.GetComponent<RectTransform>(), rect);
var targetRect = _tempObject.GetComponent<RectTransform>();
SetAnchorMiddleCenter(targetRect);
//targetRect.anchorMin = new Vector2(bounds.min.x,bounds.min.y);
//targetRect.anchorMax = new Vector2(bounds.max.x, bounds.max.y);
targetRect.sizeDelta = bounds.size;
targetRect.anchoredPosition = bounds.center;
}
public static void SetAnchorMiddleCenter(RectTransform rectTransform){
rectTransform.offsetMin = new Vector2(0.5f, 0.5f);//好像是不对的,哈哈哈
rectTransform.offsetMax = new Vector2(0.5f, 0.5f);
rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
}
}
计算锚点中心
public static Vector2 ToCenterPivot(RectTransform rect,Vector2 srcPos)
{
//设:p1==原点;p2==最终我们要的目标点
//公式:p1+p=p2
var pWidth = (rect.sizeDelta.x ) * (rect.pivot.x-0.5f);
var pHeight = (rect.sizeDelta.y ) * (rect.pivot.y-0.5f);
Vector2 nodeOffset = Vector2.zero;
if (rect.parent != null)
{
// //anchor和父节点有关
var parentSize = rect.parent.GetComponent<RectTransform>().sizeDelta;
var x = (0.5f-(rect.anchorMin.x+(rect.anchorMax.x - rect.anchorMin.x) / 2)) * parentSize.x;
var y = (0.5f-(rect.anchorMin.y+(rect.anchorMax.y - rect.anchorMin.y) / 2)) * parentSize.y;
nodeOffset =new Vector2(x,y);
}
return srcPos + new Vector2(pWidth, pHeight) + nodeOffset;
}