当前位置:   article > 正文

unity目录滑动展示效果_unity左右滑动切换图片

unity左右滑动切换图片

一:只能滑动一个按钮的记录

一、效果展示

 图片可以外部修改,但是目前这个包图片数量是固定的6个,可以再inspector面板中修改图片的个数,对应文字的个数和StreamingAssets中的图片个数也应该修改,

按左右两边的按钮也可以左右滑动,一次只能滑动一个图片,

适用于做一个项目的目录

二:代码

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. using DG.Tweening;
  7. public class SliderCanMoveScrollView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
  8. {
  9. //content的长度计算方法:(cellLength + spacing)*(num-1)
  10. private RectTransform contentTrans;
  11. private float beginMousePositionX;
  12. private float endMousePositionX;
  13. private ScrollRect scrollRect;
  14. public int cellLength;
  15. public int spacing;
  16. public int leftOffset;
  17. private float moveOneItemLength;
  18. private Vector3 currentContentLocalPos;//上一次的位置
  19. private Vector3 contentInitPos;//Content初始位置
  20. private Vector2 contentTransSize;//Content初始大小
  21. public int totalItemNum;
  22. private int currentIndex;
  23. public Text pageText;
  24. public bool needSendMessage;
  25. private void Awake()
  26. {
  27. scrollRect = GetComponent<ScrollRect>();
  28. contentTrans = scrollRect.content;
  29. moveOneItemLength = cellLength + spacing;
  30. currentContentLocalPos = contentTrans.localPosition;
  31. contentTransSize = contentTrans.sizeDelta;
  32. contentInitPos = contentTrans.localPosition;
  33. currentIndex = 1;
  34. if (pageText != null)
  35. {
  36. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  37. }
  38. }
  39. public void Init()
  40. {
  41. currentIndex = 1;
  42. if (contentTrans != null)
  43. {
  44. contentTrans.localPosition = contentInitPos;
  45. currentContentLocalPos = contentInitPos;
  46. if (pageText != null)
  47. {
  48. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  49. }
  50. }
  51. }
  52. /// <summary>
  53. /// 通过拖拽与松开来达成翻页效果
  54. /// </summary>
  55. /// <param name="eventData"></param>
  56. public void OnEndDrag(PointerEventData eventData)
  57. {
  58. endMousePositionX = Input.mousePosition.x;
  59. float offSetX = 0;
  60. float moveDistance = 0;//当次需要滑动的距离
  61. offSetX = beginMousePositionX - endMousePositionX;
  62. if (offSetX > 0)//右滑
  63. {
  64. if (currentIndex >= totalItemNum)
  65. {
  66. return;
  67. }
  68. if (needSendMessage)
  69. {
  70. UpdatePanel(true);
  71. }
  72. moveDistance = -moveOneItemLength;
  73. currentIndex++;
  74. }
  75. else//左滑
  76. {
  77. if (currentIndex <= 1)
  78. {
  79. return;
  80. }
  81. if (needSendMessage)
  82. {
  83. UpdatePanel(false);
  84. }
  85. moveDistance = moveOneItemLength;
  86. currentIndex--;
  87. }
  88. if (pageText != null)
  89. {
  90. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  91. }
  92. DOTween.To(() => contentTrans.localPosition, lerpValue => contentTrans.localPosition = lerpValue, currentContentLocalPos + new Vector3(moveDistance, 0, 0), 0.5f).SetEase(Ease.OutQuint);
  93. currentContentLocalPos += new Vector3(moveDistance, 0, 0);
  94. }
  95. /// <summary>
  96. /// 按钮来控制翻书效果
  97. /// </summary>
  98. public void ToNextPage()
  99. {
  100. float moveDistance = 0;
  101. if (currentIndex >= totalItemNum)
  102. {
  103. return;
  104. }
  105. moveDistance = -moveOneItemLength;
  106. currentIndex++;
  107. if (pageText != null)
  108. {
  109. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  110. }
  111. if (needSendMessage)
  112. {
  113. UpdatePanel(true);
  114. }
  115. DOTween.To(() => contentTrans.localPosition, lerpValue => contentTrans.localPosition = lerpValue, currentContentLocalPos + new Vector3(moveDistance, 0, 0), 0.5f).SetEase(Ease.OutQuint);
  116. currentContentLocalPos += new Vector3(moveDistance, 0, 0);
  117. }
  118. public void ToLastPage()
  119. {
  120. float moveDistance = 0;
  121. if (currentIndex <= 1)
  122. {
  123. return;
  124. }
  125. moveDistance = moveOneItemLength;
  126. currentIndex--;
  127. if (pageText != null)
  128. {
  129. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  130. }
  131. if (needSendMessage)
  132. {
  133. UpdatePanel(false);
  134. }
  135. DOTween.To(() => contentTrans.localPosition, lerpValue => contentTrans.localPosition = lerpValue, currentContentLocalPos + new Vector3(moveDistance, 0, 0), 0.5f).SetEase(Ease.OutQuint);
  136. currentContentLocalPos += new Vector3(moveDistance, 0, 0);
  137. }
  138. public void OnBeginDrag(PointerEventData eventData)
  139. {
  140. beginMousePositionX = Input.mousePosition.x;
  141. }
  142. //设置Content的大小
  143. public void SetContentLength(int itemNum)
  144. {
  145. contentTrans.sizeDelta = new Vector2(contentTrans.sizeDelta.x + (cellLength + spacing) * (itemNum - 1), contentTrans.sizeDelta.y);
  146. totalItemNum = itemNum;
  147. }
  148. //初始化Content的大小
  149. public void InitScrollLength()
  150. {
  151. contentTrans.sizeDelta = contentTransSize;
  152. }
  153. //发送翻页信息的方法
  154. public void UpdatePanel(bool toNext)
  155. {
  156. if (toNext)
  157. {
  158. gameObject.SendMessageUpwards("ToNextLevel");
  159. }
  160. else
  161. {
  162. gameObject.SendMessageUpwards("ToLastLevel");
  163. }
  164. }
  165. }

(其中content长度的计算方法也再代码中有)

图片外部导入

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. using UnityEngine;
  7. using UnityEngine.UI;
  8. /// <summary>
  9. /// 图片外部加载
  10. /// </summary>
  11. public class ImageManage : MonoBehaviour
  12. {
  13. List<Sprite> imageList = new List<Sprite>(); //加载的图片的列表
  14. [SerializeField] List<GameObject> images = new List<GameObject>(); //图片列表
  15. [SerializeField] List<Text> texts = new List<Text>(); //图片名称列表
  16. void Start()
  17. {
  18. LoadAllPic();
  19. for (int i = 0; i < imageList.Count; i++)
  20. {
  21. //将图片赋值到预制体上
  22. images[i].GetComponent<Image>().sprite = imageList[i];
  23. }
  24. }
  25. string[] dirs;
  26. //外部加载图片
  27. void LoadAllPic()
  28. {
  29. string imgtype = "*.JPG|*.PNG";
  30. string[] ImageType = imgtype.Split('|');
  31. List<string> filePathList = new List<string>();
  32. string[] dirs1 = Directory.GetFiles(Application.streamingAssetsPath + "/image/", ImageType[0]);
  33. List<string> dirs1List = new List<string>(dirs1);
  34. string[] dirs2 = Directory.GetFiles(Application.streamingAssetsPath + "/image/", ImageType[1]);
  35. //当两种格式都存在时,将第二个数组中的内容加入到第一个数组中去
  36. if (ImageType[0] != null && ImageType[1] != null)
  37. {
  38. for (int m = 0; m < dirs2.Length; m++)
  39. {
  40. string dir2 = dirs2[m];
  41. dirs1List.Add(dir2);
  42. }
  43. dirs = dirs1List.ToArray();
  44. }
  45. //当只有jpg格式时,将数组内容赋值
  46. else if (ImageType[0] != null && ImageType[1] == null)
  47. dirs = dirs1;
  48. //当只有png格式时,将数组内容赋值
  49. else if (ImageType[0] == null && ImageType[1] != null)
  50. dirs = dirs2;
  51. for (int j = 0; j < dirs.Length; j++)
  52. {
  53. Texture2D tx = new Texture2D(100, 100);
  54. tx.LoadImage(getImageByte(dirs[j]));
  55. Sprite sprite = Sprite.Create(tx, new Rect(0, 0, tx.width, tx.height), new Vector2(-500, -500));
  56. //获取sprite的名称
  57. sprite.name = Path.GetFileNameWithoutExtension(dirs[j]);
  58. //将名称用“-”分割
  59. string[] names = sprite.name.Split('-');
  60. //获取数字后面的名字并赋值
  61. texts[j].text = names[1];
  62. //将获取的图片加到图片列表中
  63. imageList.Add(sprite);
  64. }
  65. }
  66. private static byte[] getImageByte(string imagePath)
  67. {
  68. FileStream files = new FileStream(imagePath, FileMode.Open);
  69. byte[] imgByte = new byte[files.Length];
  70. files.Read(imgByte, 0, imgByte.Length);
  71. files.Close();
  72. return imgByte;
  73. }
  74. }

三:unity布局

先新建一个ScrollRect,将代码挂载再上面,然后再content中添加Grid Layout Group组件,设置左偏移量,图片大小和间隔,将这些数值设置好之后,填入SliderCanMoveScrollView 脚本中,content中Right的计算方法(每个图片的长度+间隔长度)*(图片数量-1);

例如:图片长度是900,间隔是700,数量是5个,那么content的Right值为:(900+700)*4

 两个button手动添加按钮监听就可以了。

二:一次滑动多个的记录

1、UI布局

 

二:代码 

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. using DG.Tweening;
  7. public class SlideCanCoverScrollView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
  8. {
  9. private float contentLength;//容器长度
  10. private float beginMousePostionX;
  11. private float endMousePositionX;
  12. private ScrollRect scrollRect;
  13. private float lastProportion;//上一个位置比例
  14. public int cellLength;//每个单元格长度
  15. public int spacing;//间隙
  16. public int leftOffset;//左偏移量
  17. private float upperLimit;//上限值
  18. private float lowerLimit;//下限值
  19. private float firstItemLength;//移动第一个单元格的距离
  20. private float oneItemLength;//滑动一个单元格需要的距离
  21. private float oneItemProportion;//滑动一个单元格所占比例
  22. public int totalItemNum;//共有几个单元格
  23. private int currentIndex;//当前单元格索引
  24. public Text pageText;
  25. private void Awake()
  26. {
  27. scrollRect = GetComponent<ScrollRect>();
  28. contentLength = scrollRect.content.rect.xMax - 2 * leftOffset - cellLength;
  29. firstItemLength = cellLength / 2 + leftOffset;
  30. oneItemLength = cellLength + spacing;
  31. oneItemProportion = oneItemLength / (contentLength+ oneItemLength);
  32. upperLimit = 1 - firstItemLength / contentLength;
  33. lowerLimit = firstItemLength / contentLength;
  34. currentIndex = 0;
  35. scrollRect.horizontalNormalizedPosition = 0;
  36. if (pageText != null)
  37. {
  38. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  39. }
  40. }
  41. public void Init()
  42. {
  43. lastProportion = 0;
  44. currentIndex = 0;
  45. if (scrollRect != null)
  46. {
  47. scrollRect.horizontalNormalizedPosition = 0;
  48. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  49. }
  50. }
  51. public void OnEndDrag(PointerEventData eventData)
  52. {
  53. float offSetX = 0;
  54. endMousePositionX = Input.mousePosition.x;
  55. offSetX = (beginMousePostionX - endMousePositionX) * 2;
  56. //Debug.Log("offSetX:" + offSetX);
  57. //Debug.Log("firstItemLength:" + firstItemLength);
  58. if (Mathf.Abs(offSetX) > firstItemLength)//执行滑动动作的前提是要大于第一个需要滑动的距离
  59. {
  60. if (offSetX > 0)//右滑
  61. {
  62. if (currentIndex >= totalItemNum)
  63. {
  64. return;
  65. }
  66. int moveCount =
  67. (int)((offSetX - firstItemLength) / oneItemLength) + 1;//当次可以移动的格子数目
  68. currentIndex += moveCount;
  69. if (currentIndex >= totalItemNum)
  70. {
  71. currentIndex = totalItemNum;
  72. }
  73. //当次需要移动的比例:上一次已经存在的单元格位置
  74. //的比例加上这一次需要去移动的比例
  75. lastProportion += oneItemProportion;
  76. Debug.Log(lastProportion);
  77. if (lastProportion >= upperLimit)
  78. {
  79. lastProportion = 1;
  80. }
  81. }
  82. else //左滑
  83. {
  84. if (currentIndex <= 1)
  85. {
  86. return;
  87. }
  88. int moveCount =
  89. (int)((offSetX + firstItemLength) / oneItemLength) - 1;//当次可以移动的格子数目
  90. currentIndex += moveCount;
  91. if (currentIndex <= 1)
  92. {
  93. currentIndex = 1;
  94. }
  95. //当次需要移动的比例:上一次已经存在的单元格位置
  96. //的比例加上这一次需要去移动的比例
  97. lastProportion += oneItemProportion * moveCount;
  98. if (lastProportion <= lowerLimit)
  99. {
  100. lastProportion = 0;
  101. }
  102. }
  103. if (pageText != null)
  104. {
  105. pageText.text = currentIndex.ToString() + "/" + totalItemNum;
  106. }
  107. }
  108. DOTween.To(() => scrollRect.horizontalNormalizedPosition, lerpValue => scrollRect.horizontalNormalizedPosition = lerpValue, lastProportion, 0.5f).SetEase(Ease.OutQuint);
  109. //GameManager.Instance.audioSourceManager.PlayPagingAudioClip();
  110. }
  111. public void OnBeginDrag(PointerEventData eventData)
  112. {
  113. beginMousePostionX = Input.mousePosition.x;
  114. }
  115. }

三:一次滑动一个的资源链接

图片轮播,可以用于目录,展示一个个目录中的内容,应用场景有:保卫萝卜的选项卡,时间线的展示,人物的展示等等_unity3d - Unity3D模型_U3D_免费下载-爱给网

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/606867
推荐阅读
相关标签
  

闽ICP备14008679号