using System.Collections;
using UnityEngine;
using System.IO;
public class printScreen : MonoBehaviour {
private Texture2D screenShot;
private bool shoot = false;
void Start () {
screenShot = new Texture2D(256, 256, TextureFormat.RGB24, false);
}
void Update () {
if (Input.GetKeyUp(KeyCode.Mouse0)) {
StartCoroutine(CaptureScreenshot());
}
}
void OnGUI() {
if (shoot) {
GUI.DrawTexture(new Rect(10, 10, 256, 256),
screenShot, ScaleMode.StretchToFill);
}
}
IEnumerator CaptureScreenshot() {
yield return new WaitForEndOfFrame();
screenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
screenShot.Apply();
byte[] bytes = screenShot.EncodeToPNG();
string filename = Application.dataPath + "/" + Time.time.ToString() + ".png";
Debug.Log(Application.dataPath);
File.WriteAllBytes(filename, bytes);
shoot = true;
}
}
小测试:在场景里随便添加几个方块,然后把脚本挂在相机上,运行场景
截图的位置是从屏幕的左下角开始的,如果想从中心截屏,把 ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0) 改为 ReadPixels(new Rect(Screen.width*0.5f,Screen.height*0.5f,256,256),0,0) 然后就可以了。
ReadPixels函数中的第一个参数理解为:读取的屏幕像素矩形区域是以game视窗的左下角为原点的矩形区域。第二、第三个参数是:位移参数一的偏移量,向左或向右,向上或向下 偏移。