Skip to content

Instantly share code, notes, and snippets.

@ogxd
Created June 28, 2019 18:46
Show Gist options
  • Save ogxd/8d62168997a81ac624cd06830fe54fee to your computer and use it in GitHub Desktop.
Save ogxd/8d62168997a81ac624cd06830fe54fee to your computer and use it in GitHub Desktop.
Camera (webcam or phone camera) directly in a Unity UI Image
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
[RequireComponent(typeof(AspectRatioFitter))]
public class CameraImage : MonoBehaviour {
private WebCamTexture cameraTexture;
private Image image;
private AspectRatioFitter fit;
void Start() {
// Use AspectRatioFitter's 'Aspect Mode' to control the layout
// 'Height Controls Width' works well for portrait smartphone app
fit = GetComponent<AspectRatioFitter>();
image = GetComponent<Image>();
cameraTexture = new WebCamTexture();
image.material.mainTexture = cameraTexture;
cameraTexture.Play();
}
private void Update() {
// Fix ratio issues
float ratio = 1f * cameraTexture.width / cameraTexture.height;
fit.aspectRatio = ratio;
// Fix scaling issues
float scaleY = cameraTexture.videoVerticallyMirrored ? -1f : 1f;
image.rectTransform.localScale = new Vector3(1f, scaleY, 1f);
// Fix orientation issues
int orient = -cameraTexture.videoRotationAngle;
image.rectTransform.localEulerAngles = new Vector3(0, 0, orient);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment