Unity截屏方法,在Unity中进行截屏。

来源:互联网 发布:风凰新闻软件 编辑:程序博客网 时间:2024/04/28 08:23

今天我们讨论下Unity3D的截屏方法,总共有三种方式。

1、利用Unity自带的系统方式进行截屏:
Application.CaptureScreenshot("Screenshot.png");

2、利用Texture2D.ReadPixels()方法和Texture2D.EncodeToPng()方法进行截屏并保存数据,代码如下:

using System.IO;using UnityEngine;using System.Collections;public class example : MonoBehaviour {    void Start() {        UploadPNG();    }    //开启一个携程进行截屏    IEnumerator UploadPNG() {//等待帧结束yield return new WaitForEndOfFrame();//获取到屏幕的宽高,进行全屏截图int width = Screen.width;int height = Screen.height;Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);tex.Apply();//将图片转成byte数据byte[] bytes = tex.EncodeToPNG();Destroy(tex);//利用post方法将图片数据进行上传WWWForm form = new WWWForm();form.AddField("frameCount", Time.frameCount.ToString());form.AddBinaryData("fileUpload", bytes);WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form);yield return w;if (w.error != null)print(w.error);elseprint("Finished Uploading Screenshot");}}

3、针对某个相机进行截图,代码如下所示:

Texture2D CaptureCamera(Camera camera, Rect rect)   {      // 创建一个RenderTexture对象      RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);      // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机      camera.targetTexture = rt;      camera.Render();      //如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。  //camera2.targetTexture = rt;  //camera2.Render();       // 激活这个rt, 并从中中读取像素。      RenderTexture.active = 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;  //camera2.targetTexture = null;      RenderTexture.active = null; // JC: added to avoid errors      GameObject.Destroy(rt);      // 最后将这些纹理数据,成一个png图片文件      byte[] bytes = screenShot.EncodeToPNG();      string filename = Application.dataPath + "/Screenshot.png";      System.IO.File.WriteAllBytes(filename, bytes);      Debug.Log(string.Format("截屏了一张照片: {0}", filename));      return screenShot;  }  
0 0
原创粉丝点击