在调用手机摄像头的时候,也可以用RawImage来承载手机摄像头传过来的画面。
private IEnumerator InitWebCameraCor()
{
float time = Time.time;
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
int width = Screen.width;
int height = Screen.height;
int max = height;
if(width > height )
{
max = width;
}
ScreenRawImg.GetComponent<RectTransform>().sizeDelta = new Vector2(max, max);
WebCamDevice[] devices = WebCamTexture.devices;
deviceName = devices[0].name;
m_webCameraTex = new WebCamTexture(deviceName, width, height, 30);
ScreenRawImg.texture = m_webCameraTex;
m_webCameraTex.Play();
}
Debug.LogFormat("打开相机使用了{0}秒", Time.time - time);
}
这里把RawImag设置为一个正方形,防止意外的拉伸导致画面扭曲。
因为使用的是RawImag而不是额外的Camera,在不要求效率的时候,比使用新的Camera要方便一点。
但是这个RawImage银幕需要注意一点就是,如果父体以上的物体被SetActive(false),会使得RawImage画面丢失,这时候的处理需要增加一个关闭时的调用函数。
public void Stop()
{
m_webCameraTex.Stop();
m_webCameraTex = null;
ScreenRawImg.texture = null;
}
也就是清除与WebCamera和RawImage相关的组件,这样下次再初始化WebCamera时,就能正确显示画面了。