标签:hid targe unity active enc height can src return
对相机所看的视角截屏保存为图片:
1 using UnityEngine;
2 using System.Collections;
3 using UnityEngine.UI;
4 /// <summary>
5 /// 对相机截图
6 /// </summary>
7 public class Jietu : MonoBehaviour {
8
9 public Camera camera;
10 Texture2D tex;
11 void Start()
12 {
13 tex= CaptureCamera(camera,new Rect(0,0,Screen.width,Screen.height));
14 GameObject.Find("Canvas/Image").GetComponent<Image>().sprite=Sprite.Create(tex, new Rect(0, 0,tex.width,tex.height), new Vector2(0.5f, 0.5f));
15 }
16 Texture2D CaptureCamera(Camera cam,Rect rect)
17 {
18 //创建一个RenderTexture对象
19 RenderTexture rt=new RenderTexture ((int)rect.width,(int)rect.height,0);
20 //临时设置相关相机的targetTexture为rt,并手动渲染相关相机
21 cam.targetTexture=rt;
22 cam.Render();
23 //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
24 //ps: camera2.targetTexture = rt;
25 //ps: camera2.Render();
26 //ps: -------------------------------------------------------------------
27
28 // 激活这个rt, 并从中中读取像素。
29 RenderTexture.active = rt;
30 Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24,false);
31 screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
32 screenShot.Apply();
33
34 // 重置相关参数,以使用camera继续在屏幕上显示
35 camera.targetTexture = null;
36 //ps: camera2.targetTexture = null;
37 RenderTexture.active = null; // JC: added to avoid errors
38 GameObject.Destroy(rt);
39 // 最后将这些纹理数据,成一个png图片文件
40 byte[] bytes = screenShot.EncodeToPNG();
41 string filename = Application.dataPath + "/Screenshot.png";
42 System.IO.File.WriteAllBytes(filename, bytes);
43 Debug.Log(string.Format("截了一张照片: {0}", filename));
44 return screenShot;
45 }
46 }
转载一下,以备后用。
标签:hid targe unity active enc height can src return
原文地址:http://www.cnblogs.com/atong/p/7420137.html