在做项目的过程中遇到,有些按钮字体过长,但又想让所有的按钮统一规格,保持整洁,就想到了鼠标悬停然后让字体循环播放,这样一来我们就既可以使所有的按钮统一大小,又能让用户看到所有的字体,提升用户体验。我下面介绍两种,一种是UGUI制作,一种是使用NGUI制作,其实原理都大同小异;
UGUI:首先创建一个图片,然后在创建一个图片为子物体(这里用来控制裁剪区域,可以自己调整这个裁剪区域),将此图片的透明度改为1,添加Mask组件,在为创建一个Text子物体,如图所示
通过获取裁剪区域的大小,Text总体的宽度来计算出我所要移动的偏移量,给按钮添加当鼠标移入时事件,移出时的事件,
大工告成,完美实现效果代码如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class MovieListLabel_ScrollView : MonoBehaviour
{
private Vector2 clipSize;
private Vector2 defalutPos;
private Text label;
private RectTransform rectTransform;
public GameObject Hover_Obj;
void Start()
{
rectTransform = GetComponent<RectTransform>();
label = GetComponent<Text>();
GetClipSize();
AddEventListener();
CheckLabel();
}
void CheckLabel()
{
if (GetComponent<Text>().text.Length < 5)
{
GetComponent<Text>().alignment = TextAnchor.MiddleCenter;
transform.localPosition = Vector3.zero;
enabled = false;
EventTriggerListener.Get(Hover_Obj).onEnter -= OnLabelHover;
}
}
/// <summary>
/// 获取裁剪范围
/// </summary>
private void GetClipSize()
{
clipSize.x = this.transform.parent.GetComponent<RectTransform>().rect.width;
clipSize.y = this.transform.parent.GetComponent<RectTransform>().rect.height;
defalutPos = this.transform.localPosition;
}
private void AddEventListener()
{
EventTriggerListener.Get(Hover_Obj).onEnter = OnLabelHover;
EventTriggerListener.Get(Hover_Obj).onExit = OnLabelExit;
}
public void AddAnimationPos(GameObject target, Vector3 posFrom, Vector3 posTo, float tweenTime)
{
iTween.MoveTo(gameObject, iTween.Hash("position", posTo, "islocal", true, "time", tweenTime, "easetype", iTween.EaseType.linear, "looptype", iTween.LoopType.none));
}
private void OnLabelHover(GameObject go)
{
if ((label.preferredWidth-clipSize.x+5) > 0)
{
Vector3 m_targetPos = defalutPos;
float m_dis = (label.preferredWidth-clipSize.x+5);
m_targetPos.x -= m_dis;
float m_time = m_dis * 0.02f;
AddAnimationPos(gameObject, defalutPos, m_targetPos, m_time);
}
}
private void OnLabelExit(GameObject go)
{
Destroy(this.GetComponent<iTween>());
this.transform.localPosition = defalutPos;
}
}