UGUI滚轮以鼠标位置为中心缩放图片

本文介绍了一个Unity脚本,该脚本能够通过鼠标滚轮事件实现图片的缩放,并允许用户通过鼠标点击来调整图片的中心点位置。通过计算鼠标位置与图片原中心点之间的相对距离,脚本可以动态更新图片的位置与缩放级别。

        修改图片中心点为鼠标位置,此部分通过鼠标和原中心点距离 与 图片大小的比例来算出中心点要移动的距离,然后根据鼠标和原中心点距离对图片坐标进行改变。

代码:

using UnityEngine;

public class Test: MonoBehaviour {

    public void ScrollEvent()
    {
        float delX = Input.mousePosition.x - transform.position.x;
        float delY = Input.mousePosition.y - transform.position.y;

        float scaleX = delX / GetComponent<RectTransform>().rect.width / transform.localScale.x;
        float scaleY = delY / GetComponent<RectTransform>().rect.height / transform.localScale.y;

        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            transform.localScale += Vector3.one * 0.1f;
        }
        else if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            transform.localScale += Vector3.one * -0.1f;
        }

        GetComponent<RectTransform>().pivot += new Vector2(scaleX, scaleY);
        transform.position += new Vector3(delX, delY, 0);
    }
}

滚轮事件:

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ScrollEvent: MonoBehaviour , IScrollHandler
{
    public UnityEvent scroll = new UnityEvent();

    public void OnScroll(PointerEventData eventData)
    {
        scroll.Invoke();
    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

末零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值