码迷,mamicode.com
首页 > 其他好文 > 详细

UGUI Set Anchor And Pivot

时间:2018-04-23 21:41:54      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:控制   roo   对齐   help   const   gui   模式   nts   失败   

我的环境

Unity 5.3.7p4

在运行时动态的设置UI元素的锚点和中心点。

设置Anchor

修改offsetMax不生效

使用下面这段代码设置Anchor并不会生效,尽管他和你在属性面板看到的值是一样的。

retRoot.offsetMin = Vector2(0,0)
retRoot.offsetMax = Vector2(0,0) 

SetInsetAndSizeFromParentEdge

使用SetInsetAndSizeFromParentEdge函数来进行设定。此函数不受锚点和中心的影响,其中第一个参数代表对齐方式,第二个参数为距离边界的距离,第三个参数为宽度或高度。

示例:

---设置为左上角
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, height)

修改Anchor不会影响Pivot

修改Anchor之后,并不会影响Pivot

设置Pivot(中心点)

pivot是一个0~1之间的值 示例:retRoot.pivot = Vector2(0, 0)

其中0,0为左下角

当你要做动画,设置父容器的Pivot就可以控制动画的出现方向

查看Pivot

在Editor的工具栏将Pivot的模式设置为这个模式(Pivot Local),才能查看到正确的Pivot。

技术分享图片

示例代码

设置左上、左下、右上、右下四个锚点,并同时设置中心点。


---@param retRoot UnityEngine.RectTransform
function TipsHelper.SetTipsAnchor(retRoot, anchor, width, height)
    if not retRoot then
        print("[error] SetAnchor失败,RectTransform不能为空")
        return
    end
    if anchor == Constants.Anchor.LeftTop then
        retRoot.pivot = Vector2(0, 1)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, height)
    elseif anchor == Constants.Anchor.LeftBottom then
        retRoot.pivot = Vector2(0, 0)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, height)
    elseif anchor == Constants.Anchor.RightTop then
        retRoot.pivot = Vector2(1, 1)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, width)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, height)
    elseif anchor == Constants.Anchor.RightBottom then
        retRoot.pivot = Vector2(1, 0)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, width)
        retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, height)
    end
end

参考资料

参考:http://www.arkaistudio.com/blog/334/unity/unity-ugui-%E5%8E%9F%E7%90%86%E7%AF%87%E4%B8%89%EF%BC%9Arecttransform

UGUI Set Anchor And Pivot

标签:控制   roo   对齐   help   const   gui   模式   nts   失败   

原文地址:https://www.cnblogs.com/zhaoqingqing/p/8884303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!