未运行情况
#if UNITY_EDITOR
string deskTopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
RenderTexture.active = captureCamera.targetTexture;
Texture2D tex = new Texture2D(captureCamera.targetTexture.width, captureCamera.targetTexture.height, TextureFormat.ARGB32, false);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
RenderTexture.active = null;
byte[] bytes = tex.EncodeToJPG();
System.IO.File.WriteAllBytes(
deskTopPath + "\\绘画截图\\" + System.DateTime.Now.Ticks + ".jpg", bytes);
#endif
运行情况下
using System.IO;
using UnityEngine;
public class Capture : MonoBehaviour
{
public float picWidth = 1920f;
public float picHeight = 1080f;
//文件名(时间戳)
string fileName;
//文件路径
string filePath;
void Start()
{
filePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop)
+ "\\全景图\\";//桌面文件夹
if (Directory.Exists(filePath) == false)//如果没有找到这个文件夹就创建一个
{
Directory.CreateDirectory(filePath);
}
fileName = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
CameraCapture(Camera.main);
}
}
/// <summary>
/// 截取图片
/// </summary>
/// <param name="m_Camera"></param>
/// <param name="filename"></param>
///
Texture2D t2d;
void CameraCapture(Camera m_Camera)
{
RenderTexture rt = new RenderTexture((int)picWidth, (int)picHeight, 16);
m_Camera.targetTexture = rt;
m_Camera.Render();
RenderTexture.active = rt;
Texture2D t = new Texture2D((int)picWidth, (int)picHeight);
t.ReadPixels(new Rect(0, 0, t.width, t.height), 0, 0);
t.Apply();
t2d = t;
//数据保存路径
string path = filePath + fileName + ".png";
System.IO.File.WriteAllBytes(path, t.EncodeToPNG());
m_Camera.targetTexture = null;
}
}