unity UI Tookit 屏幕坐标转panel坐标

前提:在Expend模式下的转换,其实和canvas是一样的

以当前鼠标位置为例,pos就是屏幕坐标转换过来的panel坐标,官方给出的转换API如下

Vector2 pos = RuntimePanelUtils.ScreenToPanel(m_VisualElement.panel, new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y));

为什么是 Screen.height - Input.mousePosition.y ,因为panel界面的原点在左上。

原理如下:

UIDocument document = GetComponent<UIDocument>();

//计算出预设panel的比值和当前坐标的比值,例如我设定的referenceResolutio为1920*1080

Vector2Int PanelSetting = document.panelSettings.referenceResolution;
if (PanelSetting.x / PanelSetting.y < Screen.width / Screen.height)

{

        // 当我屏幕坐标宽高比大于设定宽高比的比值时,比如我的屏幕像素为2000*1000,1920/1080<2000/1000,那么转换比值就会以高度为基准,整个屏幕的尺寸会被转换为(2000*(1080/1000)=2160)*1080的panel尺寸
        ScreenRatio = (float)PanelSetting.y / Screen.height;

}
else

{

         // 当我屏幕坐标宽高比小于设定宽高比的比值时,比如我的屏幕像素为1500*1000,1920/1080>1500/1000,那么转换比值就会以宽度为基准,整个屏幕的尺寸会被转换为1920*(1000*(1920/1500)=1280)的panel尺寸

        ScreenRatio = (float)PanelSetting.x / Screen.width;

}

//进行转换,其实就是屏幕坐标*比值

Vector2 pos = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y)* ScreenRatio;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值