服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - UGUI轮播图组件实现方法详解

UGUI轮播图组件实现方法详解

2022-07-09 09:11阿循 C#

这篇文章主要为大家详细介绍了UGUI轮播图组件的实现方法,支持自动轮播、手势切换等功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了UGUI轮播图组件实现的具体代码,供大家参考,具体内容如下

要用到,于是就自已做了一个,自认为封装上还是OK的,开发于unity5.1.2。

支持自动轮播、手势切换、代码调用切换,支持水平和竖直两个方向以及正负方向轮播,轮播索引改变有回调可以用,也可以获取到当前处于正中的子元素。

要注意的是,向轮播列表中加入新元素不能直接setparent,要调用该组件的AddChild方法

下面是鄙人的代码:

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

用法和ugui的scrollrect组件是差不多的,因为本来在drag事件上有所借鉴
例图如下:

UGUI轮播图组件实现方法详解

另外,它不会像ugui的几个布局组件一样自动去改变子元素的大小为cellsize,cellsize只是虚拟的子元素容器大小,这个要注意下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/yangxun983323204/article/details/52860443

延伸 · 阅读

精彩推荐
  • C#C#获取进程或线程相关信息的方法

    C#获取进程或线程相关信息的方法

    这篇文章主要介绍了C#获取进程或线程相关信息的方法,涉及C#操作进程及线程的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    我心依旧7432021-10-21
  • C#C++调用C#的DLL程序实现方法

    C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,具有一定的参考价值,下面就让我们一起来学习吧...

    work hard work smart10092021-10-29
  • C#webBrowser执行js的方法,并返回值,c#后台取值的实现

    webBrowser执行js的方法,并返回值,c#后台取值的实现

    下面小编就为大家带来一篇webBrowser执行js的方法,并返回值,c#后台取值的实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过...

    C#教程网11082021-12-13
  • C#C#实现简单的计算器功能完整实例

    C#实现简单的计算器功能完整实例

    这篇文章主要介绍了C#实现简单的计算器功能,结合完整实例形式分析了C#实现常见的数学运算、进制转换等相关操作技巧与界面布局方法,需要的朋友可以参...

    5t4rk11042022-01-20
  • C#C#实现用栈求逆序的方法示例

    C#实现用栈求逆序的方法示例

    这篇文章主要介绍了C#实现用栈求逆序的方法,涉及C#数据结构中栈的压入与取出相关操作技巧,需要的朋友可以参考下...

    a7719485246392022-01-17
  • C#C# 遍历枚举类型的所有元素

    C# 遍历枚举类型的所有元素

    写个小东西,刚好用到枚举类型,需要显示在DropDownList控件中。尝试了下,用如下方法可以实现...

    C#教程网5562020-12-18
  • C#C#实现动态数据绘图graphic的方法示例

    C#实现动态数据绘图graphic的方法示例

    这篇文章主要介绍了C#实现动态数据绘图graphic的方法,结合实例形式分析了C#根据动态数据绘制2D数据表格的相关操作技巧,需要的朋友可以参考下...

    5t4rk6242022-01-21
  • C#C#如何利用反射将枚举绑定到下拉框详解

    C#如何利用反射将枚举绑定到下拉框详解

    这篇文章主要给大家介绍了关于C#如何利用反射将枚举绑定到下拉框的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参...

    孤者自清8222022-02-25