原理
ScrollRect类有个参数:horizontalNormalizedPosition,这是水平滚动的进度值,取值范围为:0-1。通过这个参数我们就可以划分分页的区域了,比如:现在是需要分3页滚动,那么进度值就可以分为3块:0、0.5、1。之后通过3个函数便可以实现翻页效果:OnBeginDrag、OnDrag、OnEndDrag
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class PageChange : MonoBehaviour, IBeginDragHandler,IEndDragHandler,IDragHandler
{
public int pageNum = 3;
private int nowPage = 0;
public Transform itemModle;
private Transform content;
private ScrollRect sRect;
private float[] pagePosi;
private void Awake()
{
content = this.transform.Find("Viewport/Content");
sRect = this.GetComponent<ScrollRect>();
pagePosi = new float[pageNum];
//为content加上布局
ContentSizeFitter contentSizeFitter = content.GetComponent<ContentSizeFitter>();
if(contentSizeFitter == null)
{
contentSizeFitter = content.gameObject.AddComponent<ContentSizeFitter>();
}
contentSizeFitter.horizontalFit = ContentSizeFitter.FitMode.MinSize;
contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.MinSize;
HorizontalLayoutGroup horizontalLayoutGroup = content.GetComponent<HorizontalLayoutGroup>();
if(horizontalLayoutGroup == null)
{
horizontalLayoutGroup = content.gameObject.AddComponent<HorizontalLayoutGroup>();
}
horizontalLayoutGroup.childControlHeight = false;
horizontalLayoutGroup.childControlWidth = false;
}
// Start is called before the first frame update
void Start()
{
for(int i =0; i<pageNum;i++)
{
Transform g = Instantiate(itemModle,content);
g.GetComponent<Image>().color = RandomColor();//弄个随机颜色,好区分各个分页
pagePosi[i] = i / ((pageNum - 1) * 1.0f);//计算每个分页的进度值
}
}
// Update is called once per frame
void Update()
{
}
public void OnBeginDrag(PointerEventData eventData)
{
//throw new System.NotImplementedException();
print("begin Drag");
print(sRect.horizontalNormalizedPosition);
}
public void OnDrag(PointerEventData eventData)
{
int leftPage = nowPage - 1 >= 0 ? nowPage - 1 : 0;
int rightPage = nowPage + 1 < pageNum ? nowPage + 1 : pageNum - 1;
//限制一下,最多只能翻一页
if (sRect.horizontalNormalizedPosition < pagePosi[leftPage])
{
sRect.horizontalNormalizedPosition = pagePosi[leftPage];
}
else if(sRect.horizontalNormalizedPosition > pagePosi[rightPage])
{
sRect.horizontalNormalizedPosition = pagePosi[rightPage];
}
}
public void OnEndDrag(PointerEventData eventData)
{
print("end Drag");
//计算该翻到哪一页
float offsetValue = sRect.horizontalNormalizedPosition - pagePosi[nowPage];
if (offsetValue > pagePosi[1]/3)
{
nowPage = nowPage + 1 < pageNum ? nowPage + 1 : pageNum - 1;
}
else if (offsetValue < -pagePosi[1]/3)
{
nowPage = nowPage - 1 >= 0 ? nowPage - 1 : 0;
}
sRect.horizontalNormalizedPosition = pagePosi[nowPage];
}
/// <summary>
/// 随机颜色
/// </summary>
/// <returns></returns>
private Color RandomColor()
{
//随机颜色的HSV值,饱和度不变,只改变H值
//H、S、V三个值的范围都是在0~1之间
float h = Random.Range(0f, 1f);//随机值
float s = 0.3f;//设置饱和度为定值
Color color = Color.HSVToRGB(h, s, 1);
return color;
}
}