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 實現(xiàn)NGUI滾動面板UICenterOnChild功能
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門蛹头,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人戏溺,你說我怎么就攤上這事渣蜗。” “怎么了旷祸?”我有些...
- 文/不壞的土叔 我叫張陵袍睡,是天一觀的道長。 經(jīng)常有香客問我肋僧,道長,這世上最難降的妖魔是什么控淡? 我笑而不...
- 正文 為了忘掉前任嫌吠,我火速辦了婚禮,結(jié)果婚禮上掺炭,老公的妹妹穿的比我還像新娘辫诅。我一直安慰自己,他們只是感情好涧狮,可當(dāng)我...
- 文/花漫 我一把揭開白布炕矮。 她就那樣靜靜地躺著,像睡著了一般者冤。 火紅的嫁衣襯著肌膚如雪肤视。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼摇予,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了吗跋?” 一聲冷哼從身側(cè)響起侧戴,我...
- 正文 年R本政府宣布,位于F島的核電站租漂,受9級特大地震影響阶女,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜哩治,卻給世界環(huán)境...
- 文/蒙蒙 一秃踩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧业筏,春花似錦憔杨、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至台谢,卻和暖如春寻狂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背对碌。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- 現(xiàn)如今的生活中手機相冊,微信朋友圈等滾動視圖無處不在,此外還有很多關(guān)于滾動視圖的APP也天天出現(xiàn)在我們的生活中,今...
- 歡迎Follow我的GitHub, 關(guān)注我的簡書. 其余參考Android目錄. 本文的合集已經(jīng)編著成書,高級An...
- 什么是UI? UI即User Interface(用戶界面)的簡稱岳瞭。泛指用戶的操作界面,UI設(shè)計主要指界面的樣式蚊锹,...
- 重度污染不適合戶外運動瞳筏,開車往山里走走,聽著新下載的歌曲牡昆, 心情好起來姚炕,看路標有西山古道,滄桑感符合霧霾天兒丢烘,連春...