Unity3D的UGUI控件拖动功能实现

将下面的类挂载到要拖动的图片控件上即可:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ImageScript : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler {
    /// <summary>
    /// 拖动时显示的临时图片
    /// </summary>
    private GameObject temimage;
    /// <summary>
    /// 拖动时显示临时图片的位置信息
    /// </summary>
    private RectTransform rtsform;
    public void OnBeginDrag(PointerEventData eventData)
    {
        var canvas = FindInParents<Canvas>(gameObject);
        if (canvas == null)
            return;
        temimage = new GameObject("TemImage");
        temimage.transform.SetParent(canvas.transform);
        temimage.transform.SetAsLastSibling();
        Image img = temimage.AddComponent<Image>();
        img.sprite = GetComponent<Image>().sprite;
        rtsform = transform as RectTransform;
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
        Debug.Log("OnDrag");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        GameObject.Destroy(temimage);
        Debug.Log("OnEndDrag");
    }
    static public T FindInParents<T>(GameObject go) where T : Component
    {
        if (go == null) return null;
        var comp = go.GetComponent<T>();
        if (comp != null)
            return comp;
        var t = go.transform.parent;
        while (t != null && comp == null)
        {
            comp = t.gameObject.GetComponent<T>();
            t = t.parent;
        }
        return comp;
    }
    private void SetDraggedPosition(PointerEventData eventData)
    {
        RectTransform rt = temimage.GetComponent<RectTransform>();
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rtsform, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
            rt.rotation = rtsform.rotation;
        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值