一键设置UI锚点到自身四周

    /// 
    /// 锚点放到周身一圈
    /// 
    [ContextMenu("锚点放到周身一圈(需要先将Anchors和Pivot都设置为0.5)")]
    public void AnchorToAllOverBody()
    {
        RectTransform rectTransform = GetComponent();//获取自身RT
        RectTransform p_rectTransform = transform.parent.GetComponent();//获取父物体RT
        Vector2 ThisRect = new Vector2(rectTransform.rect.width, rectTransform.rect.height);
        Vector2 wh_Parent = new Vector2(p_rectTransform.rect.width, p_rectTransform.rect.height);
        Vector2 AnchorRect = new Vector2((wh_Parent.x / 2) + rectTransform.anchoredPosition.x, (wh_Parent.y / 2) + rectTransform.anchoredPosition.y);
        rectTransform.anchorMin = new Vector2((AnchorRect.x - (ThisRect.x / 2)) / wh_Parent.x, (AnchorRect.y - (ThisRect.y / 2)) / wh_Parent.y);
        rectTransform.anchorMax = new Vector2((AnchorRect.x + (ThisRect.x / 2)) / wh_Parent.x, (AnchorRect.y + (ThisRect.y / 2)) / wh_Parent.y);
        rectTransform.offsetMin = Vector2.zero;
        rectTransform.offsetMax = Vector2.zero;
    }

你可能感兴趣的:(unity,UGUI,UGUI,unity3d)