Unity Android端创建图片文件
公司叫我负责一个Unity的程序里头有一个功能按下截图并发送
下面是我的代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class CaptureShoot : MonoBehaviour
{
Rect rect;
public Camera screen_camera;
public GameObject Capture;
string scrPathName;
void Start()
{
rect = new Rect(0, 0, Screen.width, Screen.height);
}
//改方法被button按钮调用来创建图片
public void Testing()
{
StartCoroutine(ScreenClick());
}
IEnumerator ScreenClick()
{
yield return null;
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
Capture.SetActive(false);//隐藏按钮
screen_camera.targetTexture = rt;
screen_camera.Render();
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
Capture.SetActive(true);
// 重置相关参数,以使用camera继续在屏幕上显示
screen_camera.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
// 最后将这些纹理数据,成一个png图片文件
byte[] bytes = screenShot.EncodeToPNG();
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
string filePath = "";
switch (Application.platform)
{
case RuntimePlatform.WindowsEditor:
filePath = Application.dataPath + "/storage/emulated/0/Camera/"; //测试路径
break;
case RuntimePlatform.OSXEditor:
filePath = Application.dataPath + "/storage/emulated/0/Camera/"; //测试路径
break;
case RuntimePlatform.Android:
filePath = "/storage/emulated/0/Camera/screenshot/";//内置存储路径
break;
}
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
scrPathName = filePath + fileName;
File.WriteAllBytes(scrPathName, bytes);
string[] tempPath = { scrPathName };
ScanFile(tempPath);
ShareManager.Instance.Share(scrPathName);
yield return null;
}
public static void ScanFile(string[] path)
{
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, path, null, null);
}
}
}
}
这一段代码在无论如何在电脑上永远找不到毛病,但是我放到手机上测试的时候死活创建不出来文件。
后来我慢慢测试发现是
File.WriteAllBytes(scrPathName, bytes);
这一行代码报错 UnauthorizedAccessException
解决方法非常简单
Wirte permission 改为 External(SDCard)
此处的打开方法为 Edit → Project Settings → Player → Other Settings