Unity Scroll View图片滑动
前言
在多媒体行业中,会有许多关于播放图片的软件诞生,切换图片有比较多的方式,下面介绍比较常用的两种,一个是只切换Image的图片精灵Sprite,一个是带有滑动过程的Scroll View切换,在这个时候unity自带的Scroll View组件就派上用场了。但是Scroll View组件无法自动定位到某一张图片,想要手指滑动一次移动到某一张还是要借助代码的力量。下面就是如何切换图片的两种常用方法:
(1)切换图片精灵
这里使用一种比较常用的加载图片的方法,将需要展示的图片放置于Resources文件夹下,后续使用脚本读取,如图所示:
在创建的Image上挂载脚本ChangeImageSprite.cs
脚本内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class ChangeImageSprite : MonoBehaviour
{Image mainimg;Sprite[] change_sp;Vector3 start_pos;Vector3 end_pos;int count;// Start is called before the first frame updatevoid Start(){mainimg = transform.GetComponent<Image>();change_sp = Resources.LoadAll<Sprite>("Image");}void Update(){if (Input.touchCount>0){switch (Input.GetTouch(0).phase){case TouchPhase.Began:start_pos = Input.GetTouch(0).position;break;case TouchPhase.Moved:break;case TouchPhase.Ended:end_pos = Input.GetTouch(0).position;float offset = end_pos.x - start_pos.x;//向左滑动if (offset < 0){if (count < change_sp.Length - 1){count++;}}//向右滑动else if (offset > 0){if (count > 0){count--;}}mainimg.sprite = change_sp[count];break;}}}
}
演示效果如下:
(2)Scroll View播放
将Scroll View调整到相应大小,选择方向(本案例为横向)如图所示:
Content添加Content Size Fitter和Grid Layout Group,调整组件设置,如图所示:
将图片添加到Content下面:
为Scroll View挂上脚本,脚本如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;public class ScrollViewScript : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{private float movespeed; private int pageCount = 1; Transform content;private ScrollRect Rect;private float pageIndex; private bool isDrag = false; private List<float> PageList = new List<float> { 0 }; private float targetPos = 0;private float nowindex = 0; private float beginDragPos;private float endDragPos;private float sensitivity = 0.5f; void Awake(){Rect = this.GetComponent<ScrollRect>();InitPageList();movespeed = 10;}void InitPageList(){content = transform.Find("Viewport/Content");pageIndex = (content.childCount / pageCount)-1;if (content != null && content.childCount != 0){for (float i = 1; i <= pageIndex; i++){PageList.Add((i / pageIndex));}}}void Update(){if (!isDrag){ Rect.horizontalNormalizedPosition = Mathf.Lerp(Rect.horizontalNormalizedPosition, targetPos, Time.deltaTime * movespeed);}}public void OnBeginDrag(PointerEventData eventData){isDrag = true;beginDragPos = Rect.horizontalNormalizedPosition;}public void OnEndDrag(PointerEventData eventData){isDrag = false;endDragPos = Rect.horizontalNormalizedPosition;endDragPos = endDragPos > beginDragPos ? endDragPos + sensitivity : endDragPos - sensitivity;float offset = endDragPos-beginDragPos;if (offset<0){nowindex = Mathf.Clamp(nowindex - 1, 0, pageIndex);targetPos = PageList[Convert.ToInt32(nowindex)];}else if(offset>0){nowindex = Mathf.Clamp(nowindex + 1, 0, pageIndex);targetPos = PageList[Convert.ToInt32(nowindex)];}}
}
效果演示: