Home Unity中的截图方法
Post
Cancel

Unity中的截图方法

使用ScreenCapture工具类

1
2
3
// 只能截全屏,不能针对相机,不能缩放
string path = Application.persistentDataPath + "/OneShot" + Time.realtimeSinceStartup.ToString() + ".png";
ScreenCapture.CaptureScreenshot(path, superSize);

利用 Texture2D读取屏幕像素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int width = Screen.width;
int height = Screen.height;

// 读取屏幕像素并存成Texture2D
var screenCapture = new Texture2D(width, height, TextureFormat.RGB24, false);
// 读取屏幕像素信息并存储为纹理数据
screenCapture.ReadPixels(new Rect(0, 0, width, height), destX, destY);
		// Rect定义截取的区域, 左下角为(0,0),右上角为(width, height), destX,destY是偏移
screenCapture.Apply();

// 采样以缩小截图的分辨率
int targetWidth = (int) (screenCapture.width * 0.2f);
int targetHeight = (int) (screenCapture.height * 0.2f);

var targetCapture = new Texture2D(targetWidth, targetHeight, screenCapture.format, false);
Color[] rpixels = targetCapture.GetPixels(0);
       
float incX=((float)1/screenCapture.width)*((float)screenCapture.width/targetWidth);
float incY=((float)1/screenCapture.height)*((float)screenCapture.height/targetHeight);
for(int px=0; px<rpixels.Length; px++) {
    rpixels[px] = screenCapture.GetPixelBilinear(incX*((float)px%targetWidth), incY*Mathf.Floor(px/targetWidth));
}
targetCapture.SetPixels(rpixels, 0);
targetCapture.Apply();

// 把Texture2D编码并存储
byte[] bytes = targetCapture.EncodeToJPG();
string path = Application.persistentDataPath + "/ScreenShot" + level + ".png";
System.IO.File.WriteAllBytes(path, bytes);

报错

1
2
3
4
5
6
7
ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
图片应该先在Camera渲染完,存进缓冲之后再ReadPixels。

解决方法一: 使用协程,yield return new WaitForEndOfFrame(); 之后再ReadPixels
解决方法二: 在OnPostRender() 里处理, OnPostRender()只有在相机下才会执行

利用相机截图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// RT的depth设置成0的话,渲染出的画面会有问题
//指定相机渲染并存成Texture2D

// 创建一个RenderTexture对象
var rt = new RenderTexture(720, 1280, depth); 
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
MainCamera.targetTexture = rt; 
MainCamera.Render();
// 激活这个rt, 并读取屏幕像素信息并存储为纹理数据
RenderTexture.active = rt; 
var screenCapture = new Texture2D(720, 1280, TextureFormat.ARGB32, false);
screenCapture.ReadPixels(new Rect(0, 0, 720, 1280), 0, 0);
screenCapture.Apply();
// 重置相关参数,以使用camera继续在屏幕上显示 
MainCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);

// 采样以缩小截图的分辨率
2
// 把Texture2D编码并存储
2
This post is licensed under CC BY 4.0 by the author.
Contents