博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
对相机所看的视角截屏保存为图片
阅读量:4635 次
发布时间:2019-06-09

本文共 1917 字,大约阅读时间需要 6 分钟。

对相机所看的视角截屏保存为图片:

1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 ///  5 /// 对相机截图 6 ///  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().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 }
View Code

转载一下,以备后用。

转载于:https://www.cnblogs.com/atong/p/7420137.html

你可能感兴趣的文章
Socket
查看>>
【C#公共帮助类】10年代码,最全的系统帮助类
查看>>
JQuery UI
查看>>
张弛有度
查看>>
【ZJOI2008】树的统计(树链剖分)
查看>>
【NOIP校内模拟】T2 华莱士(环套树)
查看>>
lists,tuples and sets of Python
查看>>
Superset配置hive数据源
查看>>
查询Master下的系统表和系统视图获取数据库的信息和简单的渗透测试
查看>>
GET和POST的区别
查看>>
Sublime Text 3 及Package Control 安装(附上一个3103可用的Key)
查看>>
jvm 性能调优
查看>>
算法(第四版)C# 习题题解——1.3
查看>>
LTE QCI分类 QoS
查看>>
【Flask】flask+uwsgi+nginx环境部署
查看>>
Get MAC address using POSIX APIs
查看>>
bzoj2120
查看>>
基于uFUN开发板的心率计(一)DMA方式获取传感器数据
查看>>
【dp】船
查看>>
oracle, group by, having, where
查看>>