/* #########
############
#############
## ###########
### ###### #####
### ####### ####
### ########## ####
#### ########### ####
#### ########### #####
##### ### ######## #####
##### ### ######## ######
###### ### ########### ######
###### #### ############## ######
####### ##################### ######
####### ###################### ######
####### ###### ################# ######
####### ###### ###### ######### ######
####### ## ###### ###### ######
####### ###### ##### #####
###### ##### ##### ####
##### #### ##### ###
##### ### ### #
### ### ###
## ### ###
__________#_______####_______####______________
身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。
我们的未来没有BUG
* ==============================================================================
* Filename: Instering
* Created: 2017/8/1
* Author: WYC
* Purpose: 从主摄像机设置像素抓取图片
* ==============================================================================
*/
using UnityEngine;
using System;
using System.IO;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CaptureCamera : MonoBehaviour {
public Camera camera1;
public Rect rect;
public void OnClick()
{
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera1.targetTexture = rt;
camera1.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继续在屏幕上显示
camera1.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
// 最后将这些纹理数据,成一个png图片文件
DateTime now = DateTime.Now;
string a = now.ToString();
String[] b = a.Split('/');
b[0] = b[0] + b[1] + b[2];
String[] c = b[0].Split(':');
c[0] = c[0] + c[1] + c[2];
c[0] = "/" + c[0];
c[0] += ".png";
byte[] bytes = screenShot.EncodeToJPG();
string filename = Application.persistentDataPath + c[0];
File.WriteAllBytes(filename, bytes);
Debug.Log(string.Format("截屏了一张照片: {0}", filename));
}
}