U3D 三种实现截屏保存精彩瞬间方式
2015-11-02 12:15
260 查看
在Unity3D,实现截屏的三种实现方式:
接下来,我们来调用这三个方法实现一个简单的截图的例子:
/// <summary> /// 使用Application类下的CaptureScreenshot()方法实现截图 /// 优点:简单,可以快速地截取某一帧的画面、全屏截图 /// 缺点:不能针对摄像机截图,无法进行局部截图 /// </summary> /// <param name="mFileName">M file name.</param> private void CaptureByUnity(string mFileName) { Application.CaptureScreenshot(mFileName,0); } /// <summary> /// 根据一个Rect类型来截取指定范围的屏幕 /// 左下角为(0,0) /// </summary> /// <param name="mRect">M rect.</param> /// <param name="mFileName">M file name.</param> private IEnumerator CaptureByRect(Rect mRect,string mFileName) { //等待渲染线程结束 yield return new WaitForEndOfFrame(); //初始化Texture2D Texture2D mTexture=new Texture2D((int)mRect.width,(int)mRect.height,TextureFormat.RGB24,false); //读取屏幕像素信息并存储为纹理数据 mTexture.ReadPixels(mRect,0,0); //应用 mTexture.Apply(); //将图片信息编码为字节信息 byte[] bytes = mTexture.EncodeToPNG(); //保存 System.IO.File.WriteAllBytes(mFileName, bytes); //如果需要可以返回截图 //return mTexture; } private IEnumerator CaptureByCamera(Camera mCamera,Rect mRect,string mFileName) { //等待渲染线程结束 yield return new WaitForEndOfFrame(); //初始化RenderTexture RenderTexture mRender=new RenderTexture((int)mRect.width,(int)mRect.height,0); //设置相机的渲染目标 mCamera.targetTexture=mRender; //开始渲染 mCamera.Render(); //激活渲染贴图读取信息 RenderTexture.active=mRender; Texture2D mTexture=new Texture2D((int)mRect.width,(int)mRect.height,TextureFormat.RGB24,false); //读取屏幕像素信息并存储为纹理数据 mTexture.ReadPixels(mRect,0,0); //应用 mTexture.Apply(); //释放相机,销毁渲染贴图 mCamera.targetTexture = null; RenderTexture.active = null; GameObject.Destroy(mRender); //将图片信息编码为字节信息 byte[] bytes = mTexture.EncodeToPNG(); //保存 System.IO.File.WriteAllBytes(mFileName,bytes); //如果需要可以返回截图 //return mTexture; } }
接下来,我们来调用这三个方法实现一个简单的截图的例子:
//定义图片保存路径 private string mPath1; private string mPath2; private string mPath3; //相机 public Transform CameraTrans; void Start() { //初始化路径 mPath1=Application.dataPath+"\\ScreenShot\\ScreenShot1.png"; mPath2=Application.dataPath+"\\ScreenShot\\ScreenShot2.png"; mPath3=Application.dataPath+"\\ScreenShot\\ScreenShot3.png"; } //主方法,使用UGUI实现 void OnGUI() { if(GUILayout.Button("截图方式1",GUILayout.Height(30))){ CaptureByUnity(mPath1); } if(GUILayout.Button("截图方式2",GUILayout.Height(30))){ StartCoroutine(CaptureByRect(new Rect(0,0,1024,768),mPath2)); } if(GUILayout.Button("截图方式3",GUILayout.Height(30))){ //启用顶视图相机 CameraTrans.camera.enabled=true; //禁用主相机 Camera.main.enabled=false; StartCoroutine(CaptureByCamera(CameraTrans.camera,new Rect(0,0,1024,768),mPath3)); } }
相关文章推荐
- html 调用客户端exe并写入文本文件
- 详解Javascript中正则表达式的使用
- Android短信的发送和广播接收者实现短信的监听
- Linux系统下修改用户密码全攻略
- android编程实现图片库的封装方法
- 小胖说事47-----iOS 修复UIImagePickerController偷换StatusBar颜色的问题
- cc3200 simplelink 无线系统概况
- 设计模式之单例模式
- iOS 保存和获取本地图片的封装函数
- SQL 按指定顺序进行排序
- C# 使用Log4Net记录日志(进阶篇)
- 小胖说事46-----iOS 控制台报错:No location, value may have been optimized out
- C# 使用Log4Net记录日志(进阶篇)
- nginx 负载均衡的参数
- Android广播接实现电话的监听(电话的状态,拦截)
- 链表操作--逆序
- 球谐函数
- 用分部积分推导梯形数值积分公式
- android获取手机基本信息
- WINRAR弹窗堆栈