unity打开移动摄像头,并自适应屏幕显示摄像头数据。兼容android和ios

跨平台并自适应显示摄像头数据
新建工程并建立UI

raw_Image的参数设置如下:

 


设置两个Canvas_UI和Canvas_Web的CamRender Mode都为Screen Space - Camera,并将Camera拖入。
设置Canvas_UI的层级高于Canvas_WebCam
编写脚本,并将脚本挂在Canvas_WebCam

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MT_Camera : MonoBehaviour
{
    Transform uiRoot;
    Transform camRoot;
    RawImage cam_Video; 
    Toggle tog_togCamera;
    WebCamTexture camTexture;
    public int w_cam = 640;
    public int h_cam = 480;   
      
    private void Awake()
    {
        uiRoot = GameObject.Find("Canvas_UI").transform;
        camRoot = GameObject.Find("Canvas_WebCam").transform;
    }
    private void Start()
    {
        cam_Video = camRoot.Find("raw_Image").GetComponent<RawImage>();
        tog_togCamera = uiRoot.Find("tog_ChangeCam").GetComponent<Toggle>();
        transform.GetComponent<CanvasScaler>().referenceResolution = new  Vector2(Screen.width, Screen.height);
        tog_togCamera.onValueChanged.AddListener(changeCam);
        tog_togCamera.isOn = true;
        ///自适应屏幕分辨率显示摄像头数据
        //宽度不变,缩放高度自适应显示摄像头数据
        //cam_Video.rectTransform.sizeDelta = new Vector2(h_cam * Screen.height / w_cam, Screen.width);
        //宽度不变,缩放宽度自适应显示摄像头数据
        cam_Video.rectTransform.sizeDelta = new Vector2(Screen.height, w_cam * Screen.width / h_cam);
    }
    void changeCam(bool isOn)
    {
        StartCoroutine(CallCamera(isOn));
    }
    IEnumerator CallCamera(bool isOn)
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            if (camTexture != null)
                camTexture.Stop();         
            WebCamDevice[] cameraDevices = WebCamTexture.devices;         
            string deviceName = "";         
            for (int i = 0; i < cameraDevices.Length; i++)
            {
                //如果是前置摄像机  
                if (WebCamTexture.devices[i].isFrontFacing && isOn)
                {
                    deviceName = WebCamTexture.devices[i].name;
                    TurnCam(isOn);
                    break;
                }
                //如果是后置摄像机  
                else if (!WebCamTexture.devices[i].isFrontFacing && !isOn)
                {
                    deviceName = WebCamTexture.devices[i].name;
                    TurnCam(isOn);
                    break;
                }
            }
            camTexture = new WebCamTexture(deviceName, w_cam, h_cam, 12);

    //camTexture =new WebCamTexture(deviceName, Screen.width, Screen.height);自己测试得出经验,自适应各种屏幕尺寸
            cam_Video.texture = camTexture;         
            camTexture.Play();
        }
    }
    /// <summary>
    /// 翻转plane,正确显示摄像头数据
    /// </summary>
    /// <param name="isOn">If set to <c>true</c> is turn.</param>
    public void TurnCam(bool isOn)
    {
        #if UNITY_IOS || UNITY_IPHONE
        if (!isOn)
            cam_Video.rectTransform.localEulerAngles = new Vector3(180, 0, 90);
        else cam_Video.rectTransform.localEulerAngles = new Vector3(0, 0, -90);
        #elif UNITY_ANDROID
        if (!isOn)
            cam_Video.rectTransform.localEulerAngles = new Vector3(180, 180, 90);
        else cam_Video.rectTransform.localEulerAngles = new Vector3(0, 180, 90);
        #endif
    }
}

分别发布到xcode和android测试
项目下载链接:https://download.csdn.net/download/qq_16929759/10421612
---------------------
作者:深圳苹果-unity3d
来源:CSDN
原文:https://blog.csdn.net/qq_16929759/article/details/80355510
版权声明:本文为博主原创文章,转载请附上博文链接!

 

 

自己的demo:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Text.RegularExpressions;
using System.IO;
using cn.sharerec;

public class TKProgremVideoAndTextureRecordManager : TKUIManager
{


public Text DeviceNameText;
public RawImage cameraTexture;
public WebCamTexture webCameraTexture;
public Button ReturnButton;
//public Button SaveButton;
public Button ViedoButton;
public Button CaptureButton;
public Button CameraSwitchButton;
public Toggle changeCameraToggle;
public Toggle VideoToggle;
public ShareREC ShareRECRef;
public int captureid = 0;
public TKDeviceInformationManager TKDeviceInformationManagerRef;
public Text Videotext;
long[] listLocalVideos;
long currenyListLocalVideosPathID;
public int CurrentItemID;
public int CurrentJsonProblemOptionID;

public Button FrontButton;
public Button SideButton;
public Button LeftButton;
public Button RightButton;
public string selectCaptureDir;
public GameObject SelectDirectionPanel;
public bool IsSelectDir=true;
private void Awake()
{
OnInit();
DeviceNameText.text = TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiName;
TKGlobalData.CurrentTextureList = new List<string>();

}

//IEnumerator Start()
//{
// yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
// if (Application.HasUserAuthorization(UserAuthorization.WebCam))
// {
// WebCamDevice[] devices = WebCamTexture.devices;
// string devicename = devices[0].name;
// webCameraTexture = new WebCamTexture(devicename, Screen.width, Screen.height);
// cameraTexture.texture = webCameraTexture;
// webCameraTexture.Play();
// }
// //SaveButton.enabled = false;
//}
private void OnSetVideoPath()
{
ShareRECRef.CacheFolder = TKGlobalData.CurrentSaveDataPath + TKDataHandle.TKDataHandleInstance.CurrentWorkShops[TKGlobalData.currentSelectWorkShopID].workShopName;
ShareRECImpl.SetCacheFolder(ShareRECRef.CacheFolder);
}
////启用此本脚本就启用摄像头
private void OnEnable()
{
//if (TKDeviceInformationManagerRef != null)
//{
// captureid = TKDeviceInformationManagerRef.CurrentTextureID;
//}
Debug.LogError("****((((9");
selectCaptureDir = "";
if (!IsSelectDir)
{
SelectDirectionPanel.SetActive(false);
}
else
{
SelectDirectionPanel.SetActive(true);
}
if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCameraTexture != null)
{
webCameraTexture.Play();
}
}
//禁用此脚本时停止摄像头
private void OnDisable()
{
if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCameraTexture != null)
{
webCameraTexture.Stop();
}
}

void Update()
{

//ScreenChange();
}

int width;
/// <summary>
/// 横竖屏切换
/// </summary>
void ScreenChange()
{
if (width == Screen.width)
return;
width = Screen.width;

if (width > Screen.height)
{
cameraTexture.transform.localEulerAngles = Vector3.zero;
}
else
{
cameraTexture.transform.localEulerAngles = new Vector3(0, 0, -90);
}
}
/// <summary>
/// 切换手机前后摄像头
/// </summary>
/// <param name="isOn"></param>
void changeCam(bool isOn)
{
StartCoroutine(CallCamera(isOn));
}
IEnumerator CallCamera(bool isOn)
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (webCameraTexture != null)
webCameraTexture.Stop();
WebCamDevice[] cameraDevices = WebCamTexture.devices;
string deviceName = "";
for (int i = 0; i < cameraDevices.Length; i++)
{
//如果是前置摄像机??
if (WebCamTexture.devices[i].isFrontFacing && isOn)
{
deviceName = WebCamTexture.devices[i].name;
TurnCam(isOn);
break;
}
//如果是后置摄像机
else if (!WebCamTexture.devices[i].isFrontFacing && !isOn)
{
deviceName = WebCamTexture.devices[i].name;
TurnCam(isOn);
break;
}
}
webCameraTexture = new WebCamTexture(deviceName, Screen.width, Screen.height);
cameraTexture.texture = webCameraTexture;
webCameraTexture.Play();
}
}
///<summary>
///翻转plane,正确显示摄像头数据
///</summary>
///<param name="isOn">If set to <c>true</c> is turn.</param>
public void TurnCam(bool isOn)
{
#if UNITY_IOS || UNITY_IPHONE
if (!isOn)
cam_Video.rectTransform.localEulerAngles = new Vector3(180, 0, 90);
else cam_Video.rectTransform.localEulerAngles = new Vector3(0, 0, -90);
#elif UNITY_ANDROID
if (!isOn)
cameraTexture.rectTransform.localEulerAngles = new Vector3(0, 0, 0);
else
cameraTexture.rectTransform.localEulerAngles = new Vector3(0, 180, 0);
#endif
}

public override void OnInit()
{
OnBindEvent();

}
public override void OnBindEvent()
{
base.OnBindEvent();
EventTriggerListener.Get(ReturnButton.gameObject).onClick += OnReturnButtonClick;
//EventTriggerListener.Get(SaveButton.gameObject).onClick += OnSaveButtonClick;
//SaveButton.onClick.AddListener(delegate() { OnSaveButtonClick(SaveButton.gameObject);});
//EventTriggerListener.Get(ViedoButton.gameObject).onClick += OnViedoButtonClick;
//EventTriggerListener.Get(CaptureButton.gameObject).onClick += OnCaptureButtonClick;
CaptureButton.onClick.AddListener(delegate () { OnCaptureButtonClick(CaptureButton.gameObject); });
EventTriggerListener.Get(CameraSwitchButton.gameObject).onClick += OnCameraSwitchButtonClick;
changeCameraToggle.onValueChanged.AddListener(changeCam);
////VideoToggle.onValueChanged.AddListener(OnVideoToggleChange);
VideoToggle.onValueChanged.AddListener((bool value) => OnVideoToggleChange(VideoToggle, value));

EventTriggerListener.Get(FrontButton.gameObject).onClick += OnFrontButtonClick;
EventTriggerListener.Get(SideButton.gameObject).onClick += OnSideButtonClick;
EventTriggerListener.Get(LeftButton.gameObject).onClick += OnLeftButtonClick;
EventTriggerListener.Get(RightButton.gameObject).onClick += OnRightButtonClick;
}
private void OnFrontButtonClick(GameObject go)
{
if (go == FrontButton.gameObject)
{
OnFrontButton();
}
}
private void OnFrontButton()
{
selectCaptureDir = "正面";
SelectDirectionPanel.SetActive(false);
}
private void OnSideButtonClick(GameObject go)
{
if (go == SideButton.gameObject)
{
OnSideButton();
}
}
private void OnSideButton()
{
selectCaptureDir = "侧面";
SelectDirectionPanel.SetActive(false);

}
private void OnLeftButtonClick(GameObject go)
{
if (go == LeftButton.gameObject)
{
OnLeftButton();
}
}
private void OnLeftButton()
{
selectCaptureDir = "左侧";
SelectDirectionPanel.SetActive(false);

}
private void OnRightButtonClick(GameObject go)
{
if (go == RightButton.gameObject)
{
OnRightButton();
}
}
private void OnRightButton()
{
selectCaptureDir = "右侧";
SelectDirectionPanel.SetActive(false);
}

void OnVideoToggleChange(Toggle clickToggle, bool isOn)
{
if (isOn)
{
Videotext.text = "开始" + ShareREC.IsAvailable();
//Debug.Log(isOn);
if (ShareREC.IsAvailable())
{
//OnSetVideoPath();//更改视频保存路径失败
//Debug.Log("开始录制!");
ShareREC.StartRecorder();
ShareREC.SetText("hahahaha");
ShareREC.AddCustomAttr("test", "nihao");

}
}
else
{
Videotext.text = "停止" + ShareREC.IsAvailable();
//Debug.Log(isOn);
if (ShareREC.IsAvailable())
{
//ShareREC.ShowProfile();
//ShareREC.OnRecorderStoppedHandler = OnEndRecord;
ShareREC.StopRecorder();
ShareREC.SetText("heihei");
ShareREC.AddCustomAttr("test2", "nihao2");
TKDeviceInformationManagerRef.LocalVideoID++;
listLocalVideos = ShareREC.ListLocalVideos();
currenyListLocalVideosPathID = listLocalVideos[listLocalVideos.Length - 1];
string videoPath = ShareREC.GetLocalVideoPath(currenyListLocalVideosPathID);
TKDeviceInformationManagerRef.AddCurrentVideoDIRList(videoPath, TKDeviceInformationManagerRef.LocalVideoID.ToString());
}
}
}
//void OnEndRecord()
//{
// Debug.Log( "录制结束");
//}
private void OnReturnButtonClick(GameObject go)
{
if (go == ReturnButton.gameObject)
{
OnReturnButton();
}
}
private void OnReturnButton()
{
//Debug.Log("ReturnButton......");

Videotext.text = "结束,找不到相机" + ShareREC.IsAvailable();
//Debug.Log(isOn);
if (ShareREC.IsAvailable())
{
//ShareREC.ShowProfile();
// ShareREC.OnRecorderStoppedHandler = OnEndRecord;
ShareREC.StopRecorder();
}
TKUIStateSelect.TKUIStateSelectInstance.OnSetCurrentUiPanelsState(TKPanelType.DeviceInformationPanel);
TKUIStateSelect.TKUIStateSelectInstance.OnSetCurrentUiPanelsState(TKPanelType.DeviceInformationPanelParent);
//TKDeviceInformationManagerRef.CurrentTextureID = captureid;
}
/// <summary>
/// 保存功能去掉2019.4.3
/// </summary>
/// <param name="go"></param>
//private void OnSaveButtonClick(GameObject go)
// {
// if (go == SaveButton.gameObject)
// {
// OnSaveButton();
// }
// }
// private void OnSaveButton()
// {
// Debug.Log("SaveButton......");
// captureid--;
// TKCaptureAndVideoRecord.TKCaptureAndVideoRecordInsrance.CaptureSave(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[0].equiName+captureid,TKDataHandle.TKDataHandleInstance.CurrentWorkShops[0].workShopName);
// if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCameraTexture != null)
// {
// webCameraTexture.Play();
// }
// SaveButton.enabled = false;
// }
private void OnViedoButtonClick(GameObject go)
{
if (go == ViedoButton.gameObject)
{
OnViedoButton();
}
}
private void OnViedoButton()
{
Debug.Log("ViedoButton......");
//TKCaptureAndVideoRecord.TKCaptureAndVideoRecordInsrance.VideoTape();//此方法会截屏一大堆图片


}
private void OnCaptureButtonClick(GameObject go)
{
if (go == CaptureButton.gameObject)
{
OnCaptureButton();
}
}

private void OnCaptureButton()
{
//Debug.Log("CaptureButton......");
//captureid++;
//TKDeviceInformationManagerRef.CurrentTextureID++;//2019.6.14
CurrentJsonProblemOptionID++;
string path;
if (selectCaptureDir != "")
{
path = TKDataHandle.TKDataHandleInstance.CurrentWorkShops[TKGlobalData.currentSelectWorkShopID].workShopName + "/" + selectCaptureDir;
}
else
{
path = TKDataHandle.TKDataHandleInstance.CurrentWorkShops[TKGlobalData.currentSelectWorkShopID].workShopName;

}

TKCaptureAndVideoRecord.TKCaptureAndVideoRecordInsrance.CaptureSave(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiId + "_" + CurrentItemID + "_" + CurrentJsonProblemOptionID, path);

//TKGlobalData.CurrentTextureList.Add(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiId + "_" + captureid);
TKDeviceInformationManagerRef.currentDeviceTextureList.Add(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiId + "_" + CurrentItemID + "_" + CurrentJsonProblemOptionID);
TKDeviceInformationManagerRef.currentDeviceTextureNameList.Add(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiName + "_" + CurrentItemID + "_" + CurrentJsonProblemOptionID);
//TKCaptureAndVideoRecord.TKCaptureAndVideoRecordInsrance.CaptureSave(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[0].equiName + captureid);
///暂时这总点击一次拍摄如果不保存,第二次点击继续拍摄(不保存的功能去掉)2019.4.3
//if (captureid % 2 ==1)
//{
// SaveButton.enabled = true;
// if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCameraTexture != null)
// {
// webCameraTexture.Stop();
// }
//}
//else
//{
// SaveButton.enabled = false;
// if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCameraTexture != null)
// {
// webCameraTexture.Play();
// }
//}
}
private void OnCameraSwitchButtonClick(GameObject go)
{
if (go == CameraSwitchButton.gameObject)
{
OnCameraSwitchButton();
}
}
private void OnCameraSwitchButton()
{
Debug.Log("CameraSwitchButton......");

}
}

posted @   WalkingSnail  阅读(1904)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示