使用Texture2D.ReadPixels进行截屏


示例代码转载:https://blog.csdn.net/qq_22393417/article/details/46356791

创建纹理

RenderTex = new Texture2D(width : int, height : int, format : TextureFormat, mipmap : bool);
参数分别表示创建的宽、高、格式等信息。

使用Texture2D.ReadPixels读取像素

将我们需要的像素信息填补到上面的纹理中,使用ReadPixels (source : Rect, destX : int, destY : int, recalculateMipMaps : bool = true) 函数。具体的方式RenderTex.ReadPixels(new Rect(0, 0, RTWidth,RTHeight), 0, 0, false);其中Rect(0, 0, RTWidth,RTHeight)表示起点是(0,0),然后截取的是像素RTWidth和RTHeight。

完整的示例代码

下面展示一些 内联代码片

using UnityEngine;
using System.Collections;
using System.IO;

public class printScreen : MonoBehaviour
{

  private Texture2D screenShot;

  private bool shoot = false;

  void Start()
  {
//实例化一张你到透明通道的大小为256*256的贴图
    screenShot = new Texture2D(256,256,TextureFormat.RGB24, false);

  }

  void Update()
  {
  //点击鼠标左键的时候 截屏并保存为png图片
    if (Input.GetKeyUp(KeyCode.Mouse0))
    {
      StartCoroutine(CaptureScreenshot());
    }
  }

  void OnGUI()
  {
  //将截出的图片以填充的方式绘制到屏幕中Rect(10,10,256,256)的区域内
    if (shoot)
    {
      GUI.DrawTexture(new Rect(10,10,256,256),screenShot,ScaleMode.StretchToFill);
    }
  }

  IEnumerator CaptureScreenshot()
  {
  //只在每一帧渲染完成后才读取屏幕信息
    yield return new WaitForEndOfFrame();

    //读取屏幕像素信息并存储为纹理数据
    screenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    screenShot.Apply();// 这一句必须有,像素信息并没有保存在2D纹理贴图中

    //读取将这些纹理数据,成一个png图片文件
    byte[] bytes = screenShot.EncodeToPNG();
    string filename = Application.dataPath +"/"+Time.time.ToString()+ ".png";

//写入文件 并且指定路径,因为使用该函数写入文件,同名的文件会被覆盖,所以,在路径中使用Time.time只是为了不出现同名文件而已, 没有什么实际的意义,只是当作个测试 
    File.WriteAllBytes(filename, bytes);
    shoot = true;
  }
}



版权声明:本文为qq_38685139原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。