unity3d用按钮进行拖拽放大或缩小panel

效果可以看下面的图,实现窗口的拖拽放大缩小


img_eee62c48dc5a710d5f9f0071067f5fde.gif
测试.gif

设置panel的瞄点为左上角,设置point值 X:0,Y:1,按钮的图右下角放置,瞄点为panel的右下角,按钮挂载当前脚本,赋值panel对象即可


img_ad8ee691c16fa83b93625c2994d6779d.png
设置.png
using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// unity实现窗口的放大缩小
/// </summary>
public class ResizePanel : MonoBehaviour, IPointerDownHandler, IDragHandler
{

    // 控制的面板
    public RectTransform panelRectTransform;
    // 最小缩放
    public Vector2 minSize = new Vector2(120, 120);
    // 最大缩放
    public Vector2 maxSize = new Vector2(800, 600);
    private Vector2 originalLocalPointerPosition;
    private Vector2 originalSizeDelta;


    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;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值