使用UGUI制作鼠标悬停字体自动移动

在做项目的过程中遇到,有些按钮字体过长,但又想让所有的按钮统一规格,保持整洁,就想到了鼠标悬停然后让字体循环播放,这样一来我们就既可以使所有的按钮统一大小,又能让用户看到所有的字体,提升用户体验。我下面介绍两种,一种是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;
    }
}


 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值