UGUI-Scroll View实现图片翻页效果

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class CenterOnTurnPage : MonoBehaviour,IPointerUpHandler,IBeginDragHandler,IEndDragHandler{

    //滚动视图
    ScrollRect scrollRect;
    //获取内容
    RectTransform content;
    //判断是否结束拖动
    bool isDrag = false;
    //目标的进度:滑动条
    float targetP = -1;
    //保存每页进度:0,0.25,0.5,0.75,1   每页进度:1/(总页数-1)*(页数-1); 
    //每页进度=单个宽度*(页数-1)/(总宽度-单个宽度)
    float[] pageProgressList;
    [SerializeField]
    private float Speed;
    // Use this for initialization
    void Start () {
        scrollRect = this.GetComponent<ScrollRect>();
        content = scrollRect.content;
        //viewport遮罩层,单个内容的宽度
        float rectWidth = scrollRect.viewport.rect.width;
        print(rectWidth);
        //整个内容的宽度
        //content size fileter
        float totalWidth = rectWidth * content.childCount;
        print(totalWidth);
        //存储每页进度
        pageProgressList = new float[content.childCount];
    //    print(totalWidth);
        for (int i = 0; i < pageProgressList.Length; i++) {
            pageProgressList[i] = rectWidth * i / (totalWidth - rectWidth);
            print(pageProgressList[i]);
        }
	}
	
	// Update is called once per frame
	void Update () {
        if (!isDrag && targetP != -1) {
            scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,targetP,Time.deltaTime*Speed);

            if (Mathf.Abs(scrollRect.horizontalNormalizedPosition - targetP) <= 0.001f) {
           
                scrollRect.horizontalNormalizedPosition = targetP;
                targetP = -1;
            }
        }
	}
    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = true;
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        isDrag = false;
        //间隔进度
        float singleP = 1f / (content.childCount - 1f);
        //应该滑动到的目标进度下标
        int index = (int)Mathf.Round(scrollRect.horizontalNormalizedPosition / singleP);
        // print(scrollRect.horizontalNormalizedPosition);
        //重置为目标进度
        targetP = pageProgressList[index];
    }

    public void OnPointerUp(PointerEventData eventData)
    {
      
    }


}

猜你喜欢

转载自blog.csdn.net/qq_42485607/article/details/82388294