using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[RequireComponent(typeof(ScrollRect))]
public class ScrollRectSnap : MonoBehaviour, IDragHandler, IEndDragHandler
{
[Range(0, 1)]
public float stepSize;
private ScrollRect scroll;
private bool LerpH;
private float targetH;
[Tooltip("Snap horizontally")]
public bool snapInH = true;
private bool LerpV;
private float targetV;
[Tooltip("Snap vertically")]
public bool snapInV = true;
public float springStrength = 16f;
// Use this for initialization
void Start()
{
scroll = gameObject.GetComponent<ScrollRect>();
scroll.inertia = false;
}
void Update()
{
if (LerpH)
{
scroll.horizontalNormalizedPosition = Mathf.Lerp(scroll.horizontalNormalizedPosition, targetH, springStrength * scroll.elasticity * Time.deltaTime);
if (Mathf.Approximately(scroll.horizontalNormalizedPosition, targetH))
LerpH = false;
}
if (LerpV)
{
scroll.verticalNormalizedPosition = Mathf.Lerp(scroll.verticalNormalizedPosition, targetV, springStrength * scroll.elasticity * Time.deltaTime);
if (Mathf.Approximately(scroll.verticalNormalizedPosition, targetV))
LerpV = false;
}
}
public void OnEndDrag(PointerEventData eventData)
{
if (scroll.horizontal && snapInH)
{
targetH = FindNearest(scroll.horizontalNormalizedPosition);
LerpH = true;
}
if (scroll.vertical && snapInV)
{
targetV = FindNearest(scroll.verticalNormalizedPosition);
LerpV = true;
}
}
public void OnDrag(PointerEventData eventData)
{
LerpH = false;
LerpV = false;
}
float FindNearest(float value)
{
value = Mathf.Clamp01(value);
int index = (int)(value / stepSize);
if (Mathf.Abs(value - index * stepSize) < Mathf.Abs(value - (index + 1) * stepSize))
return stepSize * index;
return (index + 1) * stepSize;
}
}
Unity UI system 实现NGUI滚动面板UICenterOnChild功能
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 现如今的生活中手机相册,微信朋友圈等滚动视图无处不在,此外还有很多关于滚动视图的APP也天天出现在我们的生活中,今...
- 欢迎Follow我的GitHub, 关注我的简书. 其余参考Android目录. 本文的合集已经编著成书,高级An...
- 什么是UI? UI即User Interface(用户界面)的简称。泛指用户的操作界面,UI设计主要指界面的样式,...