将下面的类挂载到要拖动的图片控件上即可:
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;
}
}
}