1. 程式人生 > >UGUI-Scroll View實現圖片翻頁效果

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)
    {
      
    }


}