欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity中的截图方法(包括全屏截图、区域截图、Camera截图和摄像头截图)

程序员文章站 2022-07-13 22:07:18
...


之前项目中需要用到截图功能,经过查找找到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类的相关方法,来实现截图功能。可分给三种情况:视口截屏、RenderTextureWebCamTexture
而无论那种情况都可以总结成三行代码,即三个步骤:

  • 先创建一个的空纹理,大小可根据实现需要设置。Texture2D texture2D = new Texture2D(int width, int height);
  • 将相应的像素信息存储入这个新建的空纹理中。texture2D.ReadPixelstexture2D.SetPixels
  • 最后,将所有像素信息,“申请”成正式的Texture2D类对象。texture2D.Apply();

视口截图

使用Texture2D类的相关方法,来实现截图功能。代码如下:

/// <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);//先创建一个的空纹理,大小可根据实现需要来设置
#pragma warning disable UNT0017 // SetPixels invocation is slow
    screenShot.ReadPixels(rect, 0, 0);//读取屏幕像素信息并存储为纹理数据,
#pragma warning restore UNT0017 // SetPixels invocation is slow
    screenShot.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等函数,获取为位数组,用于保存为图片。
除截取全屏外,也可以通过对传入的参数Rect rect的大小操控,完成对整个游戏画面中,某个区域的截图。总体的说,就是整个视口的截图方法。

RenderTexture(Camera截图)

上面的方法都是全屏截图或全屏中的某块区域,那如何只截取场景中某个或某几个这相机的图像呢?
同样,使用Texture2D类的相关方法,就可以实现,代码如下:

/// <summary>
/// 对相机截图
/// </summary>
/// <param name="camera">Camera.要被截屏的相机</param>
/// <param name="rect">Rect.截屏的区域</param>
/// <returns>The screenshot2.</returns>
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 errors
    GameObject.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中的截图方法(包括全屏截图、区域截图、Camera截图和摄像头截图)
代码中的前几行,实现的就是这个过程。然后通过系统的静态属性RenderTexture.active,使系统从对应的Camera上获取像素,然后再通过Texture2D.ReadPixelsTexture2D.Apply将截图保存成Texture2D对象,之后的操作就不用再多说了。
另外,新建RenderTexture类对象的过程可以用我刚刚提到的手动过程代替,我项目中就是这样使用的,代码如下:

/// <summary>
/// 头像截图
/// </summary>
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_EDITOR
    string path = Application.streamingAssetsPath + "/Icon/" + name;
#else
    string path = Application.persistentDataPath + "/Icon/" + name;
#endif
    byte[] 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类对象。

参考链接

  1. https://blog.csdn.net/anyuanlzh/article/details/17008909
  2. https://blog.csdn.net/lawliet_lin/article/details/82382287
相关标签: 功能 unity c#