CameraPreview.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using Rokid.UXR.Native;
  4. using Rokid.UXR.Utility;
  5. namespace Rokid.UXR.Demo
  6. {
  7. public class CameraPreview : MonoBehaviour
  8. {
  9. private bool isInit;
  10. private Texture2D previewTex;
  11. public RawImage rawImage;
  12. private int width, height;
  13. private byte[] data;
  14. public void Init()
  15. {
  16. width = NativeInterface.NativeAPI.GetPreviewWidth();
  17. height = NativeInterface.NativeAPI.GetPreivewHeight();
  18. if (NativeInterface.NativeAPI.GetGlassName().Equals("Rokid Max Plus"))
  19. {
  20. NativeInterface.NativeAPI.SetCameraPreviewDataType(3);
  21. previewTex = new Texture2D(width, height, TextureFormat.RGBA32, false);
  22. }
  23. else
  24. {
  25. NativeInterface.NativeAPI.SetCameraPreviewDataType(1);
  26. previewTex = new Texture2D(width, height, TextureFormat.BGRA32, false);
  27. }
  28. data = new byte[width * height * 4];
  29. NativeInterface.NativeAPI.OnCameraDataUpdate += OnCameraDataUpdate;
  30. isInit = true;
  31. }
  32. private void OnCameraDataUpdate(int width, int height, byte[] data, long timestamp)
  33. {
  34. Loom.QueueOnMainThread(() =>
  35. {
  36. previewTex.LoadRawTextureData(data);
  37. previewTex.Apply();
  38. rawImage.texture = previewTex;
  39. });
  40. }
  41. private void Awake()
  42. {
  43. #if !UNITY_EDITOR
  44. rawImage.color = Color.white;
  45. #endif
  46. NativeInterface.NativeAPI.StartCameraPreview();
  47. }
  48. public void Release()
  49. {
  50. if (isInit)
  51. {
  52. NativeInterface.NativeAPI.OnCameraDataUpdate -= OnCameraDataUpdate;
  53. NativeInterface.NativeAPI.StopCameraPreview();
  54. NativeInterface.NativeAPI.ClearCameraDataUpdate();
  55. isInit = false;
  56. }
  57. }
  58. private void OnDestroy()
  59. {
  60. Release();
  61. }
  62. private void OnApplicationPause(bool pauseStatus)
  63. {
  64. if (pauseStatus)
  65. {
  66. Release();
  67. }
  68. else
  69. {
  70. NativeInterface.NativeAPI.StartCameraPreview();
  71. }
  72. }
  73. private void Update()
  74. {
  75. if (isInit == false && NativeInterface.NativeAPI.IsPreviewing())
  76. {
  77. Init();
  78. }
  79. }
  80. }
  81. }