当前位置: 首页 > article >正文

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

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

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

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

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

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

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

代码实现如下:

/// <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;
}    


http://www.kler.cn/a/586175.html

相关文章:

  • 3D文物线上展览如何实现?
  • pythonSTL---sys
  • Upload-labs靶场通关(2)
  • DeepSeek 助力 C++ 开发:探索智能编程新境界
  • 大模型学习笔记------Llama 3模型架构之旋转编码(RoPE)
  • 【论文精读】Deformable DETR:用于端到端目标检测可变形 Transformer
  • PHP:从入门到进阶的全方位指南
  • 微软 System Center Configuration Manager(SCCM)的组件文件
  • tauri项目加载静态html和js文件,并打包发布
  • arm内核寄存器错误定位技巧【持续更新】
  • 生活在缝缝补补中前进
  • oralce sql 查询rownum1到1000的数据
  • 信息安全意识之安全组织架构图
  • 将 IPoIB 驱动修改为仅使用 RC 模式
  • linux(ubuntu)中Conda、CUDA安装Xinference报错ERROR: Failed to build (llama-cpp-python)
  • 操作系统知识点29
  • SpringBoot中使用kaptcha生成验证码
  • IOS兼容 - uniapp ios固定定位失效与刘海屏的坑
  • HarmonyOS第22天:解锁鸿蒙服务开发
  • object.assign和扩展运算法是深拷贝还是浅拷贝,两者区别