「Unity3D」UGUI运行时设置元素的锚点Anchor,维持元素Rect的显示不变,即待在原处

在编辑器中,通过设置Raw edit mode,可以切换两种,元素锚点的改变模式:

  • 一种是锚点单独改变,即:不开启原始模式,保持原样,改变anchoredPositionsizeDelta
  • 一种是锚点联动显示,即:开启原始模式,不保持原样,不改变anchoredPositionsizeDelta

原理很简单,anchoredPositionsizeDelta 都是相对于锚点Anchor 的,所以Anchor 变动,元素rect 保持原样,就需要改变posdelta ,而元素rect 跟着变动,就可以维持posdelta不变。

那么,在运行时用代码设置anchorMinanchorMax ,只有联动显示的模式,即相当于开启原始模式------不改变anchoredPositionsizeDelta ,改变元素rect的显示。

但有时候,我们需要只改变锚点,而保持rect显示不变------这是利用锚点适配不同分辨率后的结果------这样其父类的改变,就可以不影响子类的缩放,如:将子类锚点设置为中心点。

解决方案,就是用offsetMinoffsetMax ,来反向抵消anchorMinanchorMax 的变化,从而维持元素rect的显示不变。

代码实现如下:

cs 复制代码
/// <summary>
/// Set the anchorMin [v2] without changing the [rectTransform] display.
/// Assume [rectTransform] has a parent, because the root is rarely operated on.
/// </summary>
public static void SetAnchorMinOnly(this RectTransform rectTransform, in Vector2 v2)
{
    var offsetOriginal      = rectTransform.anchorMin - v2;
    rectTransform.anchorMin = v2;

    var parentSize          = (rectTransform.parent as RectTransform).rect.size;
    rectTransform.offsetMin = parentSize * offsetOriginal;
}  


/// <summary>
/// Set the anchorMax [v2] without changing the [rectTransform] display.
/// Assume [rectTransform] has a parent, because the root is rarely operated on.
/// </summary>
public static void SetAnchorMaxOnly(this RectTransform rectTransform, in Vector2 v2)
{
    var offsetOriginal      = rectTransform.anchorMax - v2;
    rectTransform.anchorMax = v2;

    var parentSize          = (rectTransform.parent as RectTransform).rect.size;
    rectTransform.offsetMax = parentSize * offsetOriginal;
}    
相关推荐
龚子亦2 个月前
Unity学习之UGUI进阶
学习·unity·游戏引擎·ugui
Leoysq4 个月前
【UGUI】实现点击注册按钮跳转游戏场景
游戏·unity·游戏引擎·ugui
咩咩觉主5 个月前
Unity 从零开始搭建一套简单易用的UGUI小框架 基础分析篇
unity·c#·ugui·小框架
咩咩觉主5 个月前
Unity 从零开始搭建一套简单易用的UGUI小框架 扩展与优化篇(完结)
unity·前端框架·c#·ugui
咩咩觉主5 个月前
Unity 从零开始搭建一套简单易用的UGUI小框架 功能撰写与优化篇
unity·c#·游戏引擎·ugui·小框架
Binarydog_Lee6 个月前
Unity笔记:ScrollRect代码阅读
笔记·unity·c#·ugui
PassionY7 个月前
Unity转Unreal5从入门到精通之UMG的使用
unity·ue5·游戏引擎·unreal·umg·ugui·hud
敬畏之心7 个月前
UGUI合批个人学习心得
unity·性能优化·ugui·合批
萌萌的提莫队长1 年前
Unity 布局 HorizontalLayoutGroup 多行 换行
unity·布局·layout·ugui·换行