CarouselImage.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. using UnityEngine.UI;
  2. using UnityEngine.EventSystems;
  3. using System;
  4. using UnityEngine;
  5. /// <summary>
  6. /// 图片轮播组件
  7. /// </summary>
  8. public class CarouselImage : UIBehaviour, IBeginDragHandler, IInitializePotentialDragHandler, IDragHandler, IEndDragHandler, ICanvasElement
  9. {
  10. /// <summary>
  11. /// 滚动方向H or V
  12. /// </summary>
  13. public enum AxisType
  14. {
  15. Horizontal,
  16. Vertical
  17. }
  18. /// <summary>
  19. /// 图片轮播方向
  20. /// </summary>
  21. public enum LoopDirType
  22. {
  23. RightOrUp = -1,
  24. LeftOrDown = 1,
  25. }
  26. /// <summary>
  27. /// 子物体size
  28. /// </summary>
  29. public Vector2 mCellSize;
  30. /// <summary>
  31. /// 子物体间隔
  32. /// </summary>
  33. public Vector2 mSpacing;
  34. /// <summary>
  35. /// 方向
  36. /// </summary>
  37. public AxisType MMoveAxisType;
  38. /// <summary>
  39. /// 轮播方向-- 1为向左移动,-1为向右移动
  40. /// </summary>
  41. public LoopDirType mLoopDirType = LoopDirType.LeftOrDown;
  42. /// <summary>
  43. /// Tween时的步数
  44. /// </summary>
  45. [Range(1, 500)]
  46. //public int mTweenStepNum = 150;
  47. public int mTweenStepNum = 3;
  48. /// <summary>
  49. /// 自动轮播
  50. /// </summary>
  51. public bool mAutoLoop = false;
  52. /// <summary>
  53. /// 可否拖动
  54. /// </summary>
  55. public bool mDrag = false;
  56. /// <summary>
  57. /// 下一次播放间隔时间
  58. /// </summary>
  59. public float mLoopSpaceTime = 1;
  60. /// <summary>
  61. /// 位于正中的子元素变化的事件,参数为index
  62. /// </summary>
  63. [HideInInspector]
  64. public Action<int> mOnIndexChange;
  65. /// <summary>
  66. /// 当前处于正中的元素
  67. /// </summary>
  68. public int CurrentIndex
  69. {
  70. get
  71. {
  72. return m_index;
  73. }
  74. }
  75. private bool m_Dragging = false;
  76. private bool m_IsNormalizing = false;
  77. private Vector2 m_CurrentPos;
  78. private int m_currentStep = 0;
  79. private RectTransform viewRectTran;
  80. private Vector2 m_PrePos;
  81. private int m_index = 0, m_preIndex = 0;
  82. private RectTransform header;
  83. private bool contentCheckCache = true;
  84. private float currTimeDelta = 0;
  85. private float viewRectXMin
  86. {
  87. get
  88. {
  89. Vector3[] v = new Vector3[4];
  90. viewRectTran.GetWorldCorners(v);
  91. return v[0].x;
  92. }
  93. }
  94. private float viewRectXMax
  95. {
  96. get
  97. {
  98. Vector3[] v = new Vector3[4];
  99. viewRectTran.GetWorldCorners(v);
  100. return v[3].x;
  101. }
  102. }
  103. private float viewRectYMin
  104. {
  105. get
  106. {
  107. Vector3[] v = new Vector3[4];
  108. viewRectTran.GetWorldCorners(v);
  109. return v[0].y;
  110. }
  111. }
  112. private float viewRectYMax
  113. {
  114. get
  115. {
  116. Vector3[] v = new Vector3[4];
  117. viewRectTran.GetWorldCorners(v);
  118. return v[2].y;
  119. }
  120. }
  121. public int CellCount
  122. {
  123. get
  124. {
  125. return transform.childCount;
  126. }
  127. }
  128. protected override void Awake()
  129. {
  130. base.Awake();
  131. viewRectTran = GetComponent<RectTransform>();
  132. header = GetChild(viewRectTran, 0);
  133. }
  134. public void resizeChildren()
  135. {
  136. Vector2 delta;
  137. if (MMoveAxisType == AxisType.Horizontal)
  138. {
  139. delta = new Vector2(mCellSize.x + mSpacing.x, 0);
  140. }
  141. else
  142. {
  143. delta = new Vector2(0, mCellSize.y + mSpacing.y);
  144. }
  145. for (int i = 0; i < CellCount; i++)
  146. {
  147. var t = GetChild(viewRectTran, i);
  148. if (t)
  149. {
  150. t.localPosition = delta * i;
  151. t.sizeDelta = mCellSize;
  152. }
  153. }
  154. m_IsNormalizing = false;
  155. m_CurrentPos = Vector2.zero;
  156. m_currentStep = 0;
  157. }
  158. /// <summary>
  159. /// 加子物体到当前列表的最后面
  160. /// </summary>
  161. /// <param name="t"></param>
  162. public virtual void AddChild(RectTransform t)
  163. {
  164. if (t != null)
  165. {
  166. t.SetParent(viewRectTran, false);
  167. t.SetAsLastSibling();
  168. Vector2 delta;
  169. if (MMoveAxisType == AxisType.Horizontal)
  170. {
  171. delta = new Vector2(mCellSize.x + mSpacing.x, 0);
  172. }
  173. else
  174. {
  175. delta = new Vector2(0, mCellSize.y + mSpacing.y);
  176. }
  177. if (CellCount == 0)
  178. {
  179. t.localPosition = Vector3.zero;
  180. header = t;
  181. }
  182. else
  183. {
  184. t.localPosition = delta + (Vector2)GetChild(viewRectTran, CellCount - 1).localPosition;
  185. header = GetChild(viewRectTran, 0);
  186. }
  187. }
  188. }
  189. protected override void OnEnable()
  190. {
  191. base.OnEnable();
  192. mOnIndexChange += OnChangeIndex;
  193. resizeChildren();
  194. //return;
  195. if (Application.isPlaying)
  196. {
  197. if (ContentIsLongerThanRect())
  198. {
  199. int s;
  200. do
  201. {
  202. s = GetBoundaryState();
  203. LoopCell(s);
  204. } while (s != 0);
  205. }
  206. }
  207. }
  208. protected override void OnDisable()
  209. {
  210. base.OnDisable();
  211. mOnIndexChange -= OnChangeIndex;
  212. }
  213. protected virtual void Update()
  214. {
  215. if (ContentIsLongerThanRect())
  216. {
  217. //实现在必要时loop子元素
  218. if (Application.isPlaying)
  219. {
  220. int s = GetBoundaryState();
  221. LoopCell(s);
  222. }
  223. //缓动回指定位置
  224. if (m_IsNormalizing && EnsureListCanAdjust())
  225. {
  226. if (m_currentStep == mTweenStepNum)
  227. {
  228. m_IsNormalizing = false;
  229. m_currentStep = 0;
  230. m_CurrentPos = Vector2.zero;
  231. return;
  232. }
  233. Vector2 delta = m_CurrentPos / mTweenStepNum;
  234. m_currentStep++;
  235. TweenToCorrect(-delta);
  236. }
  237. //自动loop
  238. if (mAutoLoop && !m_IsNormalizing && EnsureListCanAdjust())
  239. {
  240. currTimeDelta += Time.deltaTime;
  241. if (currTimeDelta > mLoopSpaceTime)
  242. {
  243. currTimeDelta = 0;
  244. MoveToIndex(m_index + (int)mLoopDirType);
  245. }
  246. }
  247. //检测index是否变化
  248. if (MMoveAxisType == AxisType.Horizontal)
  249. {
  250. m_index = (int)(header.localPosition.x / (mCellSize.x + mSpacing.x - 1));
  251. }
  252. else
  253. {
  254. m_index = (int)(header.localPosition.y / (mCellSize.y + mSpacing.y - 1));
  255. }
  256. if (m_index <= 0)
  257. {
  258. m_index = Mathf.Abs(m_index);
  259. }
  260. else
  261. {
  262. m_index = CellCount - m_index;
  263. }
  264. if (m_index != m_preIndex)
  265. {
  266. if (mOnIndexChange != null)
  267. {
  268. mOnIndexChange(m_index);
  269. }
  270. }
  271. m_preIndex = m_index;
  272. }
  273. }
  274. public virtual void OnBeginDrag(PointerEventData eventData)
  275. {
  276. if (!mDrag || !contentCheckCache)
  277. {
  278. return;
  279. }
  280. Vector2 vector;
  281. if (((eventData.button == PointerEventData.InputButton.Left) && this.IsActive()) && RectTransformUtility.ScreenPointToLocalPointInRectangle(this.viewRectTran, eventData.position, eventData.pressEventCamera, out vector))
  282. {
  283. this.m_Dragging = true;
  284. m_PrePos = vector;
  285. currTimeDelta = 0;
  286. }
  287. }
  288. public virtual void OnInitializePotentialDrag(PointerEventData eventData)
  289. {
  290. if (!mDrag)
  291. {
  292. return;
  293. }
  294. return;
  295. }
  296. public virtual void OnDrag(PointerEventData eventData)
  297. {
  298. if (!mDrag || !contentCheckCache)
  299. {
  300. return;
  301. }
  302. Vector2 vector;
  303. if (((eventData.button == PointerEventData.InputButton.Left) && this.IsActive()) && RectTransformUtility.ScreenPointToLocalPointInRectangle(this.viewRectTran, eventData.position, eventData.pressEventCamera, out vector))
  304. {
  305. m_IsNormalizing = false;
  306. m_CurrentPos = Vector2.zero;
  307. m_currentStep = 0;
  308. Vector2 vector2 = vector - this.m_PrePos;
  309. Vector2 vec = CalculateOffset(vector2);
  310. this.SetContentPosition(vec);
  311. m_PrePos = vector;
  312. }
  313. }
  314. /// <summary>
  315. /// 移动到指定索引
  316. /// </summary>
  317. /// <param name="ind"></param>
  318. public virtual void MoveToIndex(int ind)
  319. {
  320. if (m_IsNormalizing)
  321. {
  322. return;
  323. }
  324. if (ind == m_index)
  325. {
  326. return;
  327. }
  328. this.m_IsNormalizing = true;
  329. Vector2 offset;
  330. if (MMoveAxisType == AxisType.Horizontal)
  331. {
  332. offset = new Vector2(mCellSize.x + mSpacing.x, 0);
  333. }
  334. else
  335. {
  336. offset = new Vector2(0, mCellSize.y + mSpacing.y);
  337. }
  338. var delta = CalcCorrectDeltaPos();
  339. int vindex = m_index;
  340. m_CurrentPos = delta + offset * (ind - vindex);
  341. m_currentStep = 0;
  342. }
  343. private Vector2 CalculateOffset(Vector2 delta)
  344. {
  345. if (MMoveAxisType == AxisType.Horizontal)
  346. {
  347. delta.y = 0;
  348. }
  349. else
  350. {
  351. delta.x = 0;
  352. }
  353. return delta;
  354. }
  355. private void SetContentPosition(Vector2 position)
  356. {
  357. foreach (RectTransform i in viewRectTran)
  358. {
  359. i.localPosition += (Vector3)position;
  360. }
  361. return;
  362. }
  363. public virtual void OnEndDrag(PointerEventData eventData)
  364. {
  365. if (!mDrag || !contentCheckCache)
  366. {
  367. return;
  368. }
  369. this.m_Dragging = false;
  370. this.m_IsNormalizing = true;
  371. m_CurrentPos = CalcCorrectDeltaPos();
  372. m_currentStep = 0;
  373. }
  374. public virtual void Rebuild(CanvasUpdate executing)
  375. {
  376. return;
  377. }
  378. /// <summary>
  379. /// List是否处于可自由调整状态
  380. /// </summary>
  381. /// <returns></returns>
  382. public virtual bool EnsureListCanAdjust()
  383. {
  384. return !m_Dragging && ContentIsLongerThanRect();
  385. }
  386. /// <summary>
  387. /// 内容是否比显示范围大
  388. /// </summary>
  389. /// <returns></returns>
  390. public virtual bool ContentIsLongerThanRect()
  391. {
  392. float contentLen;
  393. float rectLen;
  394. if (MMoveAxisType == AxisType.Horizontal)
  395. {
  396. contentLen = CellCount * (mCellSize.x + mSpacing.x) - mSpacing.x;
  397. rectLen = viewRectTran.rect.xMax - viewRectTran.rect.xMin;
  398. }
  399. else
  400. {
  401. contentLen = CellCount * (mCellSize.y + mSpacing.y) - mSpacing.y;
  402. rectLen = viewRectTran.rect.yMax - viewRectTran.rect.yMin;
  403. }
  404. contentCheckCache = contentLen > rectLen;
  405. return contentCheckCache;
  406. }
  407. /// <summary>
  408. /// 检测边界情况,分为0未触界,-1左(下)触界,1右(上)触界
  409. /// </summary>
  410. /// <returns></returns>
  411. public virtual int GetBoundaryState()
  412. {
  413. RectTransform left;
  414. RectTransform right;
  415. left = GetChild(viewRectTran, 0);
  416. right = GetChild(viewRectTran, CellCount - 1);
  417. Vector3[] l = new Vector3[4];
  418. left.GetWorldCorners(l);
  419. Vector3[] r = new Vector3[4];
  420. right.GetWorldCorners(r);
  421. if (MMoveAxisType == AxisType.Horizontal)
  422. {
  423. if (l[0].x >= viewRectXMin)
  424. {
  425. return -1;
  426. }
  427. else if (r[3].x < viewRectXMax)
  428. {
  429. return 1;
  430. }
  431. }
  432. else
  433. {
  434. if (l[0].y >= viewRectYMin)
  435. {
  436. return -1;
  437. }
  438. else if (r[1].y < viewRectYMax)
  439. {
  440. return 1;
  441. }
  442. }
  443. return 0;
  444. }
  445. /// <summary>
  446. /// Loop列表,分为-1把最右(上)边一个移到最左(下)边,1把最左(下)边一个移到最右(上)边
  447. /// </summary>
  448. /// <param name="dir"></param>
  449. protected virtual void LoopCell(int dir)
  450. {
  451. if (dir == 0)
  452. {
  453. return;
  454. }
  455. RectTransform MoveCell;
  456. RectTransform Tarborder;
  457. Vector2 TarPos;
  458. if (dir == 1)
  459. {
  460. MoveCell = GetChild(viewRectTran, 0);
  461. Tarborder = GetChild(viewRectTran, CellCount - 1);
  462. MoveCell.SetSiblingIndex(CellCount - 1);
  463. }
  464. else
  465. {
  466. Tarborder = GetChild(viewRectTran, 0);
  467. MoveCell = GetChild(viewRectTran, CellCount - 1);
  468. MoveCell.SetSiblingIndex(0);
  469. }
  470. if (MMoveAxisType == AxisType.Horizontal)
  471. {
  472. TarPos = Tarborder.localPosition + new Vector3((mCellSize.x + mSpacing.x) * dir, 0, 0);
  473. }
  474. else
  475. {
  476. TarPos = (Vector2)Tarborder.localPosition + new Vector2(0, (mCellSize.y + mSpacing.y) * dir);
  477. }
  478. MoveCell.localPosition = TarPos;
  479. }
  480. /// <summary>
  481. /// 计算一个最近的正确位置
  482. /// </summary>
  483. /// <returns></returns>
  484. public virtual Vector2 CalcCorrectDeltaPos()
  485. {
  486. Vector2 delta = Vector2.zero;
  487. float distance = float.MaxValue;
  488. foreach (RectTransform i in viewRectTran)
  489. {
  490. var td = Mathf.Abs(i.localPosition.x) + Mathf.Abs(i.localPosition.y);
  491. if (td <= distance)
  492. {
  493. distance = td;
  494. delta = i.localPosition;
  495. }
  496. else
  497. {
  498. break;
  499. }
  500. }
  501. return delta;
  502. }
  503. /// <summary>
  504. /// 移动指定增量
  505. /// </summary>
  506. protected virtual void TweenToCorrect(Vector2 delta)
  507. {
  508. foreach (RectTransform i in viewRectTran)
  509. {
  510. i.localPosition += (Vector3)delta;
  511. }
  512. }
  513. private static RectTransform GetChild(RectTransform parent, int index)
  514. {
  515. if (parent == null || index >= parent.childCount)
  516. {
  517. return null;
  518. }
  519. return parent.GetChild(index) as RectTransform;
  520. }
  521. public void LayoutComplete()
  522. {
  523. }
  524. public void GraphicUpdateComplete()
  525. {
  526. }
  527. /// <summary>
  528. /// 当前中心位置index回调
  529. /// </summary>
  530. /// <param name="index"></param>
  531. public void OnChangeIndex(int index)
  532. {
  533. }
  534. }