操作步骤:创建脚步并挂载到Main Camera上
仍未解决的问题:导入到安卓平台测试时,拍照按钮不能随着屏幕旋转而变换位置;文章来源:https://www.toymoban.com/news/detail-742244.html
拍照时会把拍照按钮也截进去。文章来源地址https://www.toymoban.com/news/detail-742244.html
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime .Serialization.Formatters.Binary;
using System.Threading;
public class TakePhotoes : MonoBehaviour
{
public string deviceName;
//接收返回的图片数据
WebCamTexture tex;
void OnGUI()
{
if(GUI.Button(new Rect(Screen.width/2-Screen.width/10, Screen.height-100, Screen.width/5, 100),"捕获照片"))
{
//捕获照片
tex.Pause();
StartCoroutine(getTexture());
//重新开始
tex.Play();
}
if(tex != null)
{
// 捕获截图大小
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height-100), tex);
}
}
void Start()
{
//调用摄像头
StartCoroutine(StartCamera());
}
public IEnumerator StartCamera()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
Screen.orientation = ScreenOrientation.LandscapeLeft;
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
deviceName= devices[0].name;
tex=new WebCamTexture(deviceName, Screen.width, Screen.height-100, 60);
tex.Play();
}
}
public IEnumerator getTexture()
{
yield return new WaitForEndOfFrame();
Texture2D t=new Texture2D(Screen.width, Screen.height-100);
t.ReadPixels(new Rect(0, 100, Screen.width, Screen.height-100), 0, 0, false);
t.Apply();
byte[] byt=t.EncodeToPNG();
string path = Application.persistentDataPath;
#if UNITY_ANDROID
path = "/sdcard/DCIM/Camera";
#endif
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string savePath = path + "/" + Time.time + ".jpg";
File.WriteAllBytes(savePath, byt);
OnSaveImagesPlartform(savePath);
}
private void OnSaveImagesPlartform(string filePath)
{
#if UNITY_ANDROID && !UNITY_EDITOR
string[] paths = new string[1];
paths[0] = filePath;
using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
{
Conn.CallStatic("scanFile", playerActivity, paths, null, null);
}
}
#endif
}
}
到了这里,关于Unity3D:调用安卓摄像头拍照的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!