前提:在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;