Unity3D的UGUI控件拖动功能实现

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

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

public class ImageScript : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler {
    ///


    /// 拖动时显示的临时图片
    ///

    private GameObject temimage;
    ///
    /// 拖动时显示临时图片的位置信息
    ///

    private RectTransform rtsform;
    public void OnBeginDrag(PointerEventData eventData)
    {
        var canvas = FindInParents(gameObject);
        if (canvas == null)
            return;
        temimage = new GameObject("TemImage");
        temimage.transform.SetParent(canvas.transform);
        temimage.transform.SetAsLastSibling();
        Image img = temimage.AddComponent();
        img.sprite = GetComponent().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(GameObject go) where T : Component
    {
        if (go == null) return null;
        var comp = go.GetComponent();
        if (comp != null)
            return comp;
        var t = go.transform.parent;
        while (t != null && comp == null)
        {
            comp = t.gameObject.GetComponent();
            t = t.parent;
        }
        return comp;
    }
    private void SetDraggedPosition(PointerEventData eventData)
    {
        RectTransform rt = temimage.GetComponent();
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rtsform, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
            rt.rotation = rtsform.rotation;
        }
    }
}
 

你可能感兴趣的:(Unity3D)