Unity中的截图方法(包括全屏截图、区域截图、Camera截图和摄像头截图) Texture2D.ReadPixels 参考链接
之前项目中需要用到截图功能,经过查找找到3种方式,这里做一个记录。 Application.CaptureScreenshot
Application类下的CaptureScreenshot方法,截取的是某一帧时整个游戏的画面,或者说是全屏截图吧。
以下是两个重载的函数。其中filename参数为截图后保存下来的文件名;superSize参数为增加分辨率的因数:
//
// 摘要:
// Captures a screenshot at path filename as a PNG file.
//
// 参数:
// filename:
// Pathname to save the screenshot file to.
//
// superSize:
// Factor by which to increase resolution.
[Obsolete("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead (UnityUpgradable) -> [UnityEngine] UnityEngine.ScreenCapture.CaptureScreenshot(*)", true)]
public static void CaptureScreenshot(string filename);
//
// 摘要:
// Captures a screenshot at path filename as a PNG file.
//
// 参数:
// filename:
// Pathname to save the screenshot file to.
//
// superSize:
// Factor by which to increase resolution.
[Obsolete("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead (UnityUpgradable) -> [UnityEngine] UnityEngine.ScreenCapture.CaptureScreenshot(*)", true)]
public static void CaptureScreenshot(string filename, int superSize);
通过上面的代码也可以看出,在新版的Unity中该函数被废弃了。新的系统函数类是ScreenCapture。
ScreenCapture
以下为系统类ScreenCapture:
//
// 摘要:
// Functionality to take Screenshots.
[NativeHeader("Modules/ScreenCapture/Public/CaptureScreenshot.h")]
public static class ScreenCapture
{public static void CaptureScreenshot(string filename);//// 摘要:// Captures a screenshot at path filename as a PNG file.//// 参数:// filename:// Pathname to save the screenshot file to.//// superSize:// Factor by which to increase resolution.//// stereoCaptureMode:// Specifies the eye texture to capture when stereo rendering is enabled.public static void CaptureScreenshot(string filename, int superSize);public static void CaptureScreenshot(string filename, StereoScreenCaptureMode stereoCaptureMode);public static Texture2D CaptureScreenshotAsTexture();//// 摘要:// Captures a screenshot of the game view into a Texture2D object.//// 参数:// superSize:// Factor by which to increase resolution.//// stereoCaptureMode:// Specifies the eye texture to capture when stereo rendering is enabled.public static Texture2D CaptureScreenshotAsTexture(int superSize);public static Texture2D CaptureScreenshotAsTexture(StereoScreenCaptureMode stereoCaptureMode);//// 摘要:// Captures a screenshot of the game view into a RenderTexture object.//// 参数:// renderTexture:// RenderTexture that will get filled with the screen content.public static void CaptureScreenshotIntoRenderTexture(RenderTexture renderTexture);//// 摘要:// Enumeration specifying the eye texture to capture when using ScreenCapture.CaptureScreenshot// and when stereo rendering is enabled.public enum StereoScreenCaptureMode{//// 摘要:// The Left Eye is captured. This is the default setting for the CaptureScreenshot// method.LeftEye = 1,//// 摘要:// The Right Eye is captured.RightEye = 2,//// 摘要:// Both the left and right eyes are captured and composited into one image.BothEyes = 3}
}
在之前的用法上有新加了另外两种用法,一是将截图直接通过Texture2D获取;二是截图直接捕捉到RenderTexture中。
使用时,直接调用即可:UnityEngine.ScreenCapture.CaptureScreenshotAsTexture();。
Texture2D.ReadPixels
使用Texture2D类的相关方法,来实现截图功能。可分给三种情况:视口截屏、RenderTexture和WebCamTexture。
而无论那种情况都可以总结成三行代码,即三个步骤:
视口截图
使用Texture2D类的相关方法,来实现截图功能。代码如下:
///
/// Captures the screenshot2.
///
/// The screenshot2.
/// Rect.截图的区域,左下角为o点
Texture2D CaptureScreenshot2(Rect rect)
{Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);//先创建一个的空纹理,大小可根据实现需要来设置
#pragma warning disable UNT0017 // SetPixels invocation is slowscreenShot.ReadPixels(rect, 0, 0);//读取屏幕像素信息并存储为纹理数据,
#pragma warning restore UNT0017 // SetPixels invocation is slowscreenShot.Apply();byte[] bytes = screenShot.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件string filename = Application.dataPath + "/Screenshot.png";System.IO.File.WriteAllBytes(filename, bytes);Debug.Log(string.Format("截屏了一张图片: {0}", filename));//最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。return screenShot;
}
与上面的ScreenCapture.CaptureScreenshot一样,这个方法也是对全屏截图。核心方法就是Texture2D.ReadPixels读取屏幕像素信息;Texture2D.Apply则是正式将其申请成为Texture2D;如有需要通过EncodeToPNG等函数,获取为位数组3D道具,用于保存为图片。
除截取全屏外,也可以通过对传入的参数Rect rect的大小操控,完成对整个游戏画面中,某个区域的截图。总体的说,就是整个视口的截图方法。
RenderTexture(Camera截图)
上面的方法都是全屏截图或全屏中的某块区域,那如何只截取场景中某个或某几个这相机的图像呢?
同样,使用Texture2D类的相关方法,就可以实现,代码如下:
///
/// 对相机截图
///
/// Camera.要被截屏的相机
/// Rect.截屏的区域
/// The screenshot2.
Texture2D CaptureCamera(Camera camera, Rect rect)
{RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);//创建一个RenderTexture对象camera.targetTexture = rt;//临时设置相关相机的targetTexture为rt, 并手动渲染相关相机camera.Render();//ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。//ps: camera2.targetTexture = rt;//ps: camera2.Render();//ps: -------------------------------------------------------------------RenderTexture.active = rt;//激活这个rt, 并从中中读取像素。Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);screenShot.ReadPixels(rect, 0, 0);//注:这个时候,它是从RenderTexture.active中读取像素screenShot.Apply();//重置相关参数,以使用camera继续在屏幕上显示camera.targetTexture = null;//ps: camera2.targetTexture = null;RenderTexture.active = null; //JC: added to avoid errorsGameObject.Destroy(rt);byte[] bytes = screenShot.EncodeToPNG();//最后将这些纹理数据,成一个png图片文件string filename = Application.dataPath + "/Screenshot.png";System.IO.File.WriteAllBytes(filename, bytes);Debug.Log(string.Format("截屏了一张照片: {0}", filename));return screenShot;
}
这个方法中用到了RenderTexture类,该类的用法,一般就是在项目中新建一个RenderTexture对象,然后拖拽到场景中对应的Camera组件的targetTexture位置,如下图所示:
代码中的前几行unity 读取图片,实现的就是这个过程。然后通过系统的静态属性RenderTexture.activeunity 读取图片,使系统从对应的Camera上获取像素,然后再通过Texture2D.ReadPixels和Texture2D.Apply将截图保存成Texture2D对象,之后的操作就不用再多说了。
另外,新建RenderTexture类对象的过程可以用我刚刚提到的手动过程代替,我项目中就是这样使用的,代码如下:
///
/// 头像截图
///
public IEnumerator<string> CameraScreenshot()
{Debug.LogError("截取头像图片!");//文件名int hour = DateTime.Now.Hour;int minute = DateTime.Now.Minute;int second = DateTime.Now.Second;int year = DateTime.Now.Year;int month = DateTime.Now.Month;int day = DateTime.Now.Day;string name = string.Format("{0:D4}-{1:D2}-{2:D2}-{3:D2}-{4:D2}-{5:D2}", year, month, day, hour, minute, second);name += ".png";//截图RenderTexture.active = m_iconCamera.activeTexture;Texture2D texture2D = new Texture2D(m_iconCamera.activeTexture.width, m_iconCamera.activeTexture.height, TextureFormat.RGB24, false);Rect rect = new Rect(0, 0, m_iconCamera.activeTexture.width, m_iconCamera.activeTexture.height);texture2D.ReadPixels(rect, 0, 0);//注:这个时候,它是从RenderTexture.active中读取像素texture2D.Apply();yield return name;
#if UNITY_EDITORstring path = Application.streamingAssetsPath + "/Icon/" + name;
#elsestring path = Application.persistentDataPath + "/Icon/" + name;
#endifbyte[] pngData = texture2D.EncodeToPNG();//获取位数组File.WriteAllBytes(path, pngData);Debug.LogError("保存图片:" + path);
}
字段m_iconCamera就是场景中的有targetTexture的Camera。其原理与上面的是一样的。
WebCamTexture(摄像头截图、照相)
WebCamTexture类是Unity用于获取摄像头画面所做的系统类。其创建和使用的方法,通过搜索引擎可以找到很多,这我就不多说了。我是用其配合Texture2D类,做出照相的功能。
为了实现这个,配合上面提到的三个步骤游戏运营,就是差了,如何获取像素信息。这个就是要用到WebCamTexture类的GetPixels方法,用于获取像素数据,即Color数组(也因此第二步这里使用的是texture2D.SetPixels)。
代码如下:
Texture2D texture2D = new Texture2D(m_texture.width, m_texture.height);
#pragma warning disable UNT0017 // SetPixels invocation is slow
texture2D.SetPixels(m_texture.GetPixels());
#pragma warning restore UNT0017 // SetPixels invocation is slow
texture2D.Apply();
byte[] pngData = texture2D.EncodeToPNG();//获取位数组
其中的m_texture字段就是WebCamTexture类对象。
参考链接