标签:inverse return scrollRect ScrollView group Unity var diff UGUI
using UnityEngine;
using UnityEngine.UI;
namespace Core.Misc.Utils
{
public static class UGUIUtils
{
/// <summary>
/// ScrollView定位。自动获取子物体来得到对应scrollRect.vertical(horizontal)NormalizedPosition
/// 不支持vertical和horizontal同时勾选的情况
/// </summary>
/// <param name="inverse">从上到下,从右到左排列时勾选inverse</param>
/// <param name="pixelOffset">像素偏移,向下、向右为正</param>
/// <returns>0 ~ 1</returns>
public static float GetScrollViewNormalizedPosition(ScrollRect scrollRect, int currentIndex, bool inverse = false, float pixelOffset = 0)
{
if (scrollRect.viewport == null || scrollRect.content == null)
{
DebugEO.LogError("ScrollView的viewport或content为空");
return inverse ? 1 : 0;
}
var childTrans = scrollRect.content.GetChild(0)?.transform as RectTransform;
if (childTrans == null)
{
DebugEO.LogError("ScrollView的Content下没有物体或者物体没有RectTransform");
return inverse ? 1 : 0;
}
if (scrollRect.vertical && scrollRect.horizontal)
{
DebugEO.LogError("暂不支持vertical和horizontal同时勾选的情况");
return inverse ? 1 : 0;
}
Rect viewportRect = scrollRect.viewport.rect;
Rect contentRect = scrollRect.content.rect;
Rect childRect = childTrans.rect;
if (scrollRect.vertical)
{
var group = scrollRect.content.GetComponent<VerticalLayoutGroup>();
if (group == null)
{
DebugEO.LogError("获取VerticalLayoutGroup失败");
return inverse ? 1 : 0;
}
var diff = viewportRect.height - contentRect.height;
var elementLength = childRect.height + group.spacing;
if (inverse)
return Mathf.Clamp01((1 - currentIndex * elementLength - pixelOffset) / diff);
else
return Mathf.Clamp01((currentIndex * elementLength - pixelOffset) / diff);
}
if (scrollRect.horizontal)
{
var group = scrollRect.content.GetComponent<HorizontalLayoutGroup>();
if (group == null)
{
DebugEO.LogError("获取HorizontalLayoutGroup失败");
return inverse ? 1 : 0;
}
var diff = viewportRect.width - contentRect.width;
var elementLength = childRect.width + group.spacing;
if (inverse)
return Mathf.Clamp01((1 - currentIndex * elementLength + pixelOffset) / diff);
else
return Mathf.Clamp01((currentIndex * elementLength + pixelOffset) / diff);
}
return inverse ? 1 : 0;
}
}
}
标签:inverse,return,scrollRect,ScrollView,group,Unity,var,diff,UGUI
来源: https://blog.csdn.net/qq_41225779/article/details/111159726
本站声明:
1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。