Unity截屏小工具
前言
在unity日常开发中,有时候美工会遇到将3D场景保存为2D图片的功能,用普通的截图工具截出来的图片不是特别理想,所以需要程序员提供一个简易的截屏小工具
实现思路
1、根据主摄像机生成一个用于渲染的摄像机
2、新建一个RenderTexture,将摄像机渲染出来的画面指定给RenderTexture
3、将RenderTexture保存为图片
代码如下:
using System.IO;
using UnityEngine;
/// <summary>
/// 截屏小工具
/// </summary>
public class CaptureUtil : MonoBehaviour
{
private RenderTexture m_RenderTexture;
void Start()
{
//创建RenderTexture,保存的图片大小
m_RenderTexture = new RenderTexture(4096, 4096, 16);
m_RenderTexture.antiAliasing = 4;
//创建子摄像机
if (Camera.main)
{
GameObject newCam = Instantiate(Camera.main.gameObject);
newCam.name = "renderCamera";
newCam.transform.parent = Camera.main.transform;
newCam.transform.localPosition = Vector3.zero;
newCam.transform.localEulerAngles = Vector3.zero;
newCam.transform.localScale = Vector3.one;
//可根据自己需求修改摄像机配置
Camera camera = newCam.GetComponent<Camera>();
camera.targetTexture = m_RenderTexture;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = new Color(0, 0, 0, 0);
Destroy(newCam.GetComponent<CaptureUtil>());
Destroy(newCam.GetComponent<AudioListener>());
}
}
private void OnGUI()
{
if (GUI.Button(new Rect(0, 0, 200, 200), "Capture"))
{
SaveRenderToPng(m_RenderTexture, "D:/Capture", "Capture");
}
}
/// <summary>
/// 将rendertexture保存为Png图片
/// </summary>
/// <param name="renderT"></param>
/// <param name="folderName"></param>
/// <param name="name"></param>
/// <returns></returns>
public static Texture2D SaveRenderToPng(RenderTexture renderT, string folderName, string name)
{
int width = renderT.width;
int height = renderT.height;
Texture2D tex2d = new Texture2D(width, height, TextureFormat.ARGB32, false);
RenderTexture.active = renderT;
tex2d.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex2d.Apply();
byte[] b = tex2d.EncodeToPNG();
if (!Directory.Exists(folderName))
Directory.CreateDirectory(folderName);
FileStream file = File.Open(folderName + "/" + name + GetTimeName() + ".png", FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(b);
file.Close();
return tex2d;
}
/// <summary>
/// 保存文件名称
/// </summary>
/// <returns></returns>
public static string GetTimeName()
{
return System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() +
System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() +
System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() +
System.DateTime.Now.Millisecond.ToString();
}
}
使用说明
1、美工设置好场景中的主摄像机镜头
2、将脚本拖动到主摄像机上,运行场景
3、点击左上角Capture按钮即可
4、可以在运行起来的时候,在主摄像机下,找到renderCamera(渲染摄像机),根据自己需求调整摄像机参数