自留
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScrollView_Page : MonoBehaviour
{
private ScrollRect ScrollRect;
public RectTransform content;
private float originPos;
private float Content_spacing;
private float[] allCenterPoints;
// Use this for initialization
void Start()
{
ScrollRect = GetComponent<ScrollRect>();
if (ScrollRect.vertical)
{
Content_spacing = content.GetComponent<VerticalLayoutGroup>().spacing;
originPos = content.anchoredPosition.y;
}
else if(ScrollRect.horizontal)
{
Content_spacing = content.GetComponent<HorizontalLayoutGroup>().spacing;
originPos = content.anchoredPosition.x;
}
//获取每个content的边界 -|————|-
allCenterPoints = new float[content.childCount + 1];
for (int i = 0; i < allCenterPoints.Length; i++)
{
if (i == 0)
{
Debug.Log("check originpos " + originPos);
allCenterPoints[i] = originPos;
continue;
}
else if(i == 1)
{
allCenterPoints[i] = originPos + Vector2ToFloat(content.GetChild(i - 1).GetComponent<RectTransform>().sizeDelta) / 2f;
continue;
}
//上一个边界的一半 + 间隔 + 现在的一半
allCenterPoints[i] = allCenterPoints[i - 1] + Vector2ToFloat(content.GetChild(i - 1).GetComponent<RectTransform>().sizeDelta) / 2f
+ Vector2ToFloat(content.GetChild(i - 2).GetComponent<RectTransform>().sizeDelta) / 2f + Content_spacing;
}
for (int i = 0; i < allCenterPoints.Length; i++)
{
Debug.Log("check Limit " + i + " : " + allCenterPoints[i]);
}
}
private void BackToCurCenter()
{
float _curPos = Vector2ToFloat(content.anchoredPosition);
for (int i = 0; i < allCenterPoints.Length; i++)
{
if (_curPos > allCenterPoints[allCenterPoints.Length - 1])
{
float _center = (allCenterPoints[allCenterPoints.Length - 1] + allCenterPoints[allCenterPoints.Length - 2]) / 2f - originPos;
content.anchoredPosition = new Vector2(ScrollRect.horizontal ? _center : 0, ScrollRect.vertical ? _center : 0);
break;
}
if (_curPos < allCenterPoints[1])
{
content.anchoredPosition = new Vector2(ScrollRect.horizontal ? originPos : 0, ScrollRect.vertical ? originPos : 0);
break;
}
if (_curPos >= allCenterPoints[i] && _curPos < allCenterPoints[i + 1])
{
float _center = (allCenterPoints[i] + allCenterPoints[i + 1]) / 2f - originPos;
content.anchoredPosition = new Vector2(ScrollRect.horizontal ? _center : 0, ScrollRect.vertical ? _center : 0);*斜体样式*
break;
}
}
}
private float Vector2ToFloat(Vector2 _pos)
{
return ScrollRect.vertical ? _pos.y : _pos.x;
}
public void StartDrag()
{
}
public void EndDrag()
{
BackToCurCenter();
}
}