Skip to content

Instantly share code, notes, and snippets.

@ku6ryo
Created November 17, 2021 11:58
Show Gist options
  • Select an option

  • Save ku6ryo/8bf9c76221ca7179dac448616b2c2e75 to your computer and use it in GitHub Desktop.

Select an option

Save ku6ryo/8bf9c76221ca7179dac448616b2c2e75 to your computer and use it in GitHub Desktop.
Unity WebCam fitting to screen
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