unity c# 获取game窗口图像

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;
  }
}

猜你喜欢

转载自blog.csdn.net/qq_21743659/article/details/132362963