ResizePanel.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4. public class ResizePanel : MonoBehaviour, IPointerDownHandler, IDragHandler {
  5. public Vector2 minSize = new Vector2 (100, 100);
  6. public Vector2 maxSize = new Vector2 (400, 400);
  7. private RectTransform panelRectTransform;
  8. private Vector2 originalLocalPointerPosition;
  9. private Vector2 originalSizeDelta;
  10. void Awake () {
  11. panelRectTransform = transform.parent.GetComponent<RectTransform> ();
  12. }
  13. public void OnPointerDown (PointerEventData data) {
  14. originalSizeDelta = panelRectTransform.sizeDelta;
  15. RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, data.position, data.pressEventCamera, out originalLocalPointerPosition);
  16. }
  17. public void OnDrag (PointerEventData data) {
  18. if (panelRectTransform == null)
  19. return;
  20. Vector2 localPointerPosition;
  21. RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, data.position, data.pressEventCamera, out localPointerPosition);
  22. Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;
  23. Vector2 sizeDelta = originalSizeDelta + new Vector2 (offsetToOriginal.x, -offsetToOriginal.y);
  24. sizeDelta = new Vector2 (
  25. Mathf.Clamp (sizeDelta.x, minSize.x, maxSize.x),
  26. Mathf.Clamp (sizeDelta.y, minSize.y, maxSize.y)
  27. );
  28. panelRectTransform.sizeDelta = sizeDelta;
  29. }
  30. }