//截图方式一
private void CaptureUnity(string mFileName)
{
//全屏截图,图片保存路径,提高分辨率系数
Application.CaptureScreenshot(mFileName, 0);
}
//截图方式二
// 根据一个Rect类型来截取指定范围的屏幕
private IEnumerator CaptureByRect(Rect mRect, string mFileName)
{
//等待渲染线程结束
yield return new WaitForEndOfFrame();
//初始化Texture2D
Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.RGB24, false);
//读取屏幕像素信息并存储为纹理数据
mTexture.ReadPixels(mRect, 0, 0);
mTexture.Apply();
//将图片信息编码为字节信息
byte[] bytes = mTexture.EncodeToPNG();
//保存
System.IO.File.WriteAllBytes(mFileName, bytes);
}
//截图方式三
//以某一camera截图
private IEnumerator CaptureByCamera(Camera mCamera, Rect mRect, string mFileName)
{
yield return new WaitForEndOfFrame();
//初始化RenderTexture
RenderTexture mRender = new RenderTexture((int)mRect.width, (int)mRect.height, 0);
//设置相机的渲染目标
mCamera.targetTexture = mRender;
//开始渲染
mCamera.Render();
//激活渲染贴图读取信息
RenderTexture.active = mRender;
Texture2D mTexture = new Texture2D((int)mRect.width, (int)mRect.height, TextureFormat.RGB24, false);
//读取屏幕像素信息并存储为纹理数据
mTexture.ReadPixels(mRect, 0, 0);
mTexture.Apply();
//释放相机,销毁渲染贴图
mCamera.targetTexture = null;
RenderTexture.active = null;
GameObject.Destroy(mRender);
byte[] bytes = mTexture.EncodeToPNG();
System.IO.File.WriteAllBytes(mFileName, bytes);
}
Unity的三种截取屏幕方式
最新推荐文章于 2025-08-27 15:07:00 发布
本文介绍三种Unity中实现屏幕截图的方法:全屏截图、指定区域截图和通过Camera截图。每种方法都详细展示了代码实现过程,包括使用RenderTexture和Texture2D进行像素读取及保存。

602

被折叠的 条评论
为什么被折叠?



