using UnityEngine;
using System.Collections;
public class ScrollView : MonoBehaviour
{
public Texture[] pics_;
public GUISkin skin_;
private int nIndex_ = 0;
private Vector2 scrollPosition_;
private Rect rcList_;
private Rect rcItem_;
// Use this for initialization
void Start()
{
rcList_ = new Rect(0, 0, Screen.width * pics_.Length, Screen.height);// 总大小,这个要计算正确
rcItem_ = new Rect(0, 0, Screen.width, Screen.height); // 每个item的大小,其实这里还是可视区域的大小,如果item比较小的,可视区域另外算好
nIndex_ = 0;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.touches[0];
// 滑动
if (touch.phase == TouchPhase.Moved)
{
scrollPosition_.x -= touch.deltaPosition.x;
}
else if (touch.phase == TouchPhase.Ended)
{//滑动结束
GetIndexFromPos();
scrollPosition_.x = Screen.width * nIndex_;
}
}
}
// 这里为了提高性能,实际只画了3个图
void OnGUI()
{
GUI.skin = skin_;
scrollPosition_ = GUI.BeginScrollView(rcItem_, scrollPosition_, rcList_, false, false);
if (nIndex_ - 1 >= 0)
GUI.DrawTexture(new Rect((nIndex_ - 1) * Screen.width, 0, Screen.width, Screen.height), pics_[nIndex_ - 1], ScaleMode.StretchToFill);
GUI.DrawTexture(new Rect((nIndex_) * Screen.width, 0, Screen.width, Screen.height), pics_[nIndex_], ScaleMode.StretchToFill);
if (nIndex_ + 1 < pics_.Length)
GUI.DrawTexture(new Rect((nIndex_ + 1) * Screen.width, 0, Screen.width, Screen.height), pics_[nIndex_ + 1], ScaleMode.StretchToFill);
GUI.EndScrollView();
}
// 计算得到当前的index
private void GetIndexFromPos()
{
for (int i = pics_.Length - 1; i >= 0; i--)
{
if (scrollPosition_.x > Screen.width * (i + 0.5f))
{
nIndex_ = i + 1;
return;
}
}
nIndex_ = 0;
}
}