using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DrawRect : MonoBehaviour { public static DrawRect Instance; public DrawRect() { Instance = this; } public Image m_Image; Vector3 startPos; Vector3 endPos; public static event Action<Vector2, Vector2,Vector2> OnRectDrawEvent; /// <summary> /// 返回为true / false /// </summary> public static event Func<bool> OnRectDrawCompletedEvent; private void Update() { if (Input.GetMouseButtonDown(0)) { startPos = Input.mousePosition; m_Image.transform.position = startPos; } else if (Input.GetMouseButton(0)) { endPos = Input.mousePosition; if (endPos.x>startPos.x&&endPos.y>startPos.y) { m_Image.rectTransform.pivot = new Vector2(0,0); m_Image.rectTransform.sizeDelta = endPos - startPos; OnRectDrawEvent?.Invoke(startPos, endPos, new Vector2(0, 0)); } else if (endPos.x < startPos.x && endPos.y < startPos.y) { m_Image.rectTransform.pivot = new Vector2(1, 1); m_Image.rectTransform.sizeDelta = startPos-endPos; OnRectDrawEvent?.Invoke(startPos, endPos, new Vector2(1, 1)); } else if(endPos.x > startPos.x && endPos.y < startPos.y) { m_Image.rectTransform.pivot = new Vector2(0, 1); m_Image.rectTransform.sizeDelta = new Vector2(Mathf.Abs(endPos.x-startPos.x),Mathf.Abs(endPos.y-startPos.y)); OnRectDrawEvent?.Invoke(startPos, endPos, new Vector2(0, 1)); } else { m_Image.rectTransform.pivot = new Vector2(1, 0); m_Image.rectTransform.sizeDelta = new Vector2(Mathf.Abs(endPos.x - startPos.x), Mathf.Abs(endPos.y - startPos.y)); OnRectDrawEvent?.Invoke(startPos, endPos, new Vector2(1, 0)); } } else if (Input.GetMouseButtonUp(0)) { m_Image.rectTransform.sizeDelta = new Vector2(0,0); startPos.x = 0; startPos.y = 0; //bool isFocusFaith = OnRectDrawCompletedEvent(); } } }
标签:鼠标,Image,rectTransform,Unity,endPos,new,框选,startPos,Vector2 From: https://www.cnblogs.com/WantPeach/p/18552135