Created
November 17, 2021 11:58
-
-
Save ku6ryo/8bf9c76221ca7179dac448616b2c2e75 to your computer and use it in GitHub Desktop.
Unity WebCam fitting to screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| using UnityEngine.UI; | |
| public class Controller : MonoBehaviour | |
| { | |
| WebCamTexture webcamTexture; | |
| [SerializeField] | |
| RawImage image; | |
| void Start() | |
| { | |
| webcamTexture = new WebCamTexture(); | |
| webcamTexture.Play(); | |
| } | |
| void Resize() | |
| { | |
| var camW = (float) webcamTexture.width; | |
| var camH = (float) webcamTexture.height; | |
| var screenW = (float) Screen.width; | |
| var screenH = (float) Screen.height; | |
| var camA = camH / camW; | |
| var screenA = screenH / screenW; | |
| var ratio = screenA / camA; | |
| if (ratio > 1) | |
| { | |
| image.rectTransform.sizeDelta = new Vector2(screenH / camA, screenH); | |
| } else { | |
| image.rectTransform.sizeDelta = new Vector2(screenW, screenW * camA); | |
| } | |
| } | |
| void Update() | |
| { | |
| image.texture = webcamTexture; | |
| Resize(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment