Unity可以通过代码实现截屏及相机画面截图,具体步骤如下:
实现截屏
确定截图尺寸
首先需要确定需要截图的尺寸,可以在代码中设置。代码如下:
int screenWidth = Screen.width;
int screenHeight = Screen.height;
创建一个RenderTexture
RenderTexture是Unity中的渲染纹理,用于将摄像机或灯光渲染结果输出到纹理中。创建RenderTexture时需要指定纹理的宽度和高度,代码如下:
RenderTexture rt = new RenderTexture(screenWidth, screenHeight, 24);
设置摄像机的TargetTexture属性
将摄像机的TargetTexture属性设置为之前创建的RenderTexture,代码如下:
Camera.main.targetTexture = rt;
调用摄像机渲染
需要手动触发一次摄像机的渲染,使得摄像机将场景渲染到RenderTexture中。代码如下:
Camera.main.Render();
读取RenderTexture中的纹理
通过RenderTexture的ReadPixels方法可以将RenderTexture中的纹理读取出来,代码如下:
Texture2D screenShot = new Texture2D(screenWidth, screenHeight, TextureFormat.RGB24, false);
screenShot.ReadPixels(new Rect(0, 0, screenWidth, screenHeight), 0, 0);
screenShot.Apply();
这里创建了一个Texture2D,然后将RenderTexture中的纹理读取到Texture2D中,并调用其Apply方法。
保存截图
最后将纹理保存成文件即可,代码如下:
byte[] bytes = screenShot.EncodeToJPG();
string path = Application.dataPath + "/../" + fileName + ".jpg";
File.WriteAllBytes(path, bytes);
这里需要将Texture2D转化为byte数组,然后使用File.WriteAllBytes将其写入文件中。
根据相机画面截图
如果需要直接根据相机画面进行截图,只需要将RenderTexture的宽度和高度设置成相机的宽度和高度即可。代码如下:
Camera cam = GetComponent<Camera>();
RenderTexture rt = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
完整示例代码如下:
using UnityEngine;
using System.IO;
public class ScreenShotExample : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int screenWidth = Screen.width;
int screenHeight = Screen.height;
RenderTexture rt = new RenderTexture(screenWidth, screenHeight, 24);
Camera.main.targetTexture = rt;
Camera.main.Render();
Texture2D screenShot = new Texture2D(screenWidth, screenHeight, TextureFormat.RGB24, false);
screenShot.ReadPixels(new Rect(0, 0, screenWidth, screenHeight), 0, 0);
screenShot.Apply();
byte[] bytes = screenShot.EncodeToJPG();
string path = Application.dataPath + "/../" + fileName + ".jpg";
File.WriteAllBytes(path, bytes);
}
}
}
另外,如果需要在UI中显示截图,只需将Texture2D赋值给RawImage组件即可,代码如下:
public RawImage rawImage;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
...
Texture2D screenShot = new Texture2D(screenWidth, screenHeight, TextureFormat.RGB24, false);
screenShot.ReadPixels(new Rect(0, 0, screenWidth, screenHeight), 0, 0);
screenShot.Apply();
rawImage.texture = screenShot;
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Unity实现截屏以及根据相机画面截图 - Python技术站