首页 > Unity3D专栏 > 【Unity3D】UGUI之拖动鼠标改变部件窗口大小
2017
10-23

【Unity3D】UGUI之拖动鼠标改变部件窗口大小

1.先上效果图

【Unity3D】UGUI之拖动鼠标改变部件窗口大小 - 第1张  | Unity3D虚拟世界 

2.调整Panel的Rect transform属性

【Unity3D】UGUI之拖动鼠标改变部件窗口大小 - 第2张  | Unity3D虚拟世界

3.挂载代码即可

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
 
public class ResizePanel : MonoBehaviour, IPointerDownHandler, IDragHandler {
         
        public Vector2 minSize = new Vector2 (100, 100);
        public Vector2 maxSize = new Vector2 (400, 400);
         
        private RectTransform panelRectTransform;
        private Vector2 originalLocalPointerPosition;
        private Vector2 originalSizeDelta;
         
        void Awake () {
                panelRectTransform = transform.GetComponent<RectTransform> ();
          
        }
         
        public void OnPointerDown (PointerEventData data) {
                originalSizeDelta = panelRectTransform.sizeDelta;
                RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, data.position, data.pressEventCamera, out originalLocalPointerPosition);
        }
         
        public void OnDrag (PointerEventData data) {
                if (panelRectTransform == null)
                        return;
                 
                Vector2 localPointerPosition;
                RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, data.position, data.pressEventCamera, out localPointerPosition);
                Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;
                 
                Vector2 sizeDelta = originalSizeDelta + new Vector2 (offsetToOriginal.x, -offsetToOriginal.y);
                sizeDelta = new Vector2 (
                        Mathf.Clamp (sizeDelta.x, minSize.x, maxSize.x),
                        Mathf.Clamp (sizeDelta.y, minSize.y, maxSize.y)
                );
                 
                panelRectTransform.sizeDelta = sizeDelta;
        }
}

通过鼠标拖拽即可改变窗口大小,同样适用于ugui的其他组件



虚拟世界提醒您:如果您觉得本文不错,快快将这篇文章分享出去吧 ,感谢您的支持和关注,谢谢!
最后编辑:
作者:虚拟世界
专注互联网技术及资讯 技术研究中心|有相关Unity3D问题或者作事宜请联系我哦!
捐 赠如果您愿意花10块钱请我喝一杯咖啡的话,请用手机扫描二维码即可通过支付宝或者微信直接向我捐款,在此非常感谢您对虚拟世界的捐赠。

留下一个回复

你的email不会被公开。