Unity3d之截图方法
<h4 id="1-使用Application类下的CaptureScreenshot方法。">1、使用Application类下的CaptureScreenshot方法。</h4>
void CaptureScreen() { Application.CaptureScreenshot("Screenshot.png", 0); } 这个方法,截取的是某一帧时整个游戏的画面,或者说是全屏截图吧。
a、不能针对某一个相机(camera)的画面,进行截图。
b、对局部画面截图,实现起来不方便,效率也低,不建议在项目中使用:
虽然CaptureScreenshot这个方法呢,本身是不要做到这一点的。但是我们可以走曲线救国的路线来实现它。思路是这样的:你可以先用这个方法截图一个全屏,然后通过路径获取到这个截图;接下来就通过相关的图形类来,取得这个截图的局部区域并保存下来,这样就能得到一个局部截图了。在这里我就不实现它了,不过有兴趣的可以试试,肯定是可以实现的。
<h4 id="2-这第二个截图的方法是,使用Texture2d类下的相关方法,也可实现截图功能。">2、这第二个截图的方法是,使用Texture2d类下的相关方法,也可实现截图功能。</h4>
/// <summary> /// Captures the screenshot2. /// </summary> /// <returns>The screenshot2.</returns> /// <param name="rect">Rect.截图的区域,左下角为o点</param> Texture2D CaptureScreenshot2(Rect rect) { // 先创建一个的空纹理,大小可根据实现需要来设置 Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24,false); // 读取屏幕像素信息并存储为纹理数据, screenShot.ReadPixels(rect, 0, 0); screenShot.Apply(); // 然后将这些纹理数据,成一个png图片文件 byte[] bytes = screenShot.EncodeToPNG(); string filename = Application.dataPath + "/Screenshot.png"; System.IO.File.WriteAllBytes(filename, bytes); Debug.Log(string.Format("截屏了一张图片: {0}", filename)); // 最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。 return screenShot; } 截全屏(如下图, 注:有ui):
CaptureScreenshot2( new Rect( Screen.width*0f, Screen.height*0f, Screen.width*1f, Screen.height*1f)); 截中间4分之(如下图):
CaptureScreenshot2( new Rect( Screen.width*0.25f, Screen.height*0.25f, Screen.width*0.5f, Screen.height*0.5f)); 这里使用了几个