直接对sizeDelta属性进行赋值,其中X和Y可以对应理解成width和height
直接对anchoredPosition3D属性进行赋值,其中X、Y、Z可以对应理解成pos X、pos Y、pos Z
代码
public class ChartsScript : MonoBehaviour
{
public GameObject LeftGameObject;
public Text LeftText;
private Vector2 _sizeDelta;
private Vector3 _anchoredPosition3D;
// Start is called before the first frame update
void Start()
{
_sizeDelta = LeftGameObject.GetComponent<RectTransform>().sizeDelta;
_anchoredPosition3D = LeftGameObject.GetComponent<RectTransform>().anchoredPosition3D;
}
public void FullLeftChart()
{
if (LeftText.text.Equals("全屏"))
{
var width = UnityEngine.Screen.width;
var height = UnityEngine.Screen.height;
var rt = LeftGameObject.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(width, height);
rt.anchoredPosition3D = new Vector3(0, 0, 0);
LeftText.text = "还原";
}
else if (LeftText.text.Equals("还原"))
{
LeftText.text = "全屏";
var rt = LeftGameObject.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(_sizeDelta.x, _sizeDelta.y);
rt.anchoredPosition3D = new Vector3(_anchoredPosition3D.x, _anchoredPosition3D.y, _anchoredPosition3D.z);
}
}
}
效果
如果发现调试的时候不全屏运行,出现点击全屏没有充满屏幕,是因为Canvas Scaler设置的问题
默认是(按屏幕大小缩放)
修改成Constant Pixel Size(恒定像素大小)即可