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


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

     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 }
    View Code

    转载一下,以备后用。

  • 相关阅读:
    C# 让程序自动以管理员身份运行
    [转]SAP算号器 license key Developer Access Key 完美解决方案
    【原创】项目性能优化全纪录(一) 存储过程优化
    treeview的遍历
    .NET求职笔试题目(续)
    SQL server 数据同步 Merge 的一个小bug
    use Stored procedure return a tabel(存储过程返回table)
    四种sql server 数据库分页的测试
    十五个世界最顶级的技术类博客网站
    层的拖动与隐藏
  • 原文地址:https://www.cnblogs.com/atong/p/7420137.html
Copyright © 2020-2023  润新知