「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;
}    
相关推荐
神码编程12 小时前
【Unity】 HTFramework框架(六十五)ScrollList滚动数据列表
unity·游戏引擎·ugui
scott.cgi17 天前
「Unity3D」TextMeshPro使用TMP_InputField实现,输入框高度自动扩展与收缩
unity·ugui·textmeshpro·tmp_inputfield·inputfield高度自动化·unity输入框高度扩展·textmeshpro高度扩展
scott.cgi1 个月前
「Unity3D」TextMeshPro中的TMP_InputField,用来实现输入框的几个小问题
unity·ugui·textmeshpro·tmp_inputfield·inputfield·inputfield输入框·ugui输入框
龚子亦4 个月前
Unity学习之UGUI进阶
学习·unity·游戏引擎·ugui
Leoysq6 个月前
【UGUI】实现点击注册按钮跳转游戏场景
游戏·unity·游戏引擎·ugui
咩咩觉主7 个月前
Unity 从零开始搭建一套简单易用的UGUI小框架 基础分析篇
unity·c#·ugui·小框架
咩咩觉主7 个月前
Unity 从零开始搭建一套简单易用的UGUI小框架 扩展与优化篇(完结)
unity·前端框架·c#·ugui
咩咩觉主7 个月前
Unity 从零开始搭建一套简单易用的UGUI小框架 功能撰写与优化篇
unity·c#·游戏引擎·ugui·小框架
Binarydog_Lee8 个月前
Unity笔记:ScrollRect代码阅读
笔记·unity·c#·ugui