Unity接入WebCameraTexture

unity接入摄像头

实现功能

1.先后摄像头切换
2.摄像画面和手机屏幕保持一样
3.画面根据设备翻转
4.手动调节scale,缩放拍摄画面的比例

TODO

1.不同设备,16:9和18:9等设备,画面可能不统一。
比如:scale为0.5时,18:9手机全屏显示,16:9会有黑边。
哪位大神如果可以解决,欢迎留言。

代码:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class WebCamTool : SingletonMono
{string DeviceName;bool isFront;public WebCamTexture webCamera;public AspectRatioFitter fit;public RawImage background;public float scale = 0.5f;//根据不同设备定义public void StartWebCamera(RawImage raw, bool front = false){background = raw;isFront = front;fit = background.GetComponent();if (fit == null){fit = background.gameObject.AddComponent();fit.aspectMode = AspectRatioFitter.AspectMode.EnvelopeParent;}StartCoroutine(CoLoadWebCamera());}public void StopWebCamera(){if (webCamera != null)webCamera.Stop();webCamera = null;}public void Destroy(){StopWebCamera();Destroy(gameObject);}/// /// 更新画面的翻转和角度/// void Update(){if (webCamera == null)return;float ratio = (float)webCamera.width / (float)webCamera.height;fit.aspectRatio = ratio; // Set the aspect ratio  float scaleY = webCamera.videoVerticallyMirrored ? -1f : 1f; // Find if the camera is mirrored or not  background.rectTransform.localScale = new Vector3(scale, scaleY* scale, scale); // Swap the mirrored camera  int orientY = isFront ? 180 : 0;//front and back switchint orientZ = -webCamera.videoRotationAngle;background.rectTransform.localEulerAngles = new Vector3(0, orientY, orientZ);}///     /// 初始化摄像头  ///     IEnumerator CoLoadWebCamera(){yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);if (Application.HasUserAuthorization(UserAuthorization.WebCam)){WebCamDevice[] devices = WebCamTexture.devices;if (devices.Length > 0){for (int i = 0; i < devices.Length; i++){if (devices[i].isFrontFacing == isFront){DeviceName = devices[i].name;webCamera = new WebCamTexture(DeviceName, Screen.width, Screen.height, 60);background.texture = webCamera;webCamera.Play();break;}}}}}}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部