Skip to content

Instantly share code, notes, and snippets.

@jesliwang
Last active January 29, 2019 06:59
Show Gist options
  • Save jesliwang/5704e19f5198dbcba435eb50a5978b2b to your computer and use it in GitHub Desktop.
Save jesliwang/5704e19f5198dbcba435eb50a5978b2b to your computer and use it in GitHub Desktop.
截图
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
public class CaptureScreen : MonoBehaviour {
public bool Capture;
private void Update() {
if(Capture)
{
Capture = false;
StartCoroutine(CaptureTexture());
}
}
IEnumerator CaptureTexture()
{
yield return new WaitForEndOfFrame();
var screenSnapshot = new Texture2D( Screen.width, Screen.height, TextureFormat.RGBA32, false, false );
screenSnapshot.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0, false );
screenSnapshot.Apply();
byte[] bytes = screenSnapshot.EncodeToPNG();
string path = Application.dataPath + "/../" + (System.DateTime.Now).ToBinary().ToString() + ".png";
Debug.LogError("SavePath=" + path);
FileStream file = File.Open(path , FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(screenSnapshot);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
[RequireComponent(typeof(Camera))]
public class CaptureScreen : MonoBehaviour {
void OnGUI() {
if(GUI.Button(new Rect(Vector2.zero, 100 * Vector2.one), "截屏"))
{
StartCoroutine(CaptureTexture());
}
}
IEnumerator CaptureTexture()
{
var cam = GetComponent<Camera>();
RenderTexture rt = RenderTexture.GetTemporary(Screen.width, Screen.height, 0, RenderTextureFormat.ARGB32);
cam.targetTexture = rt;
yield return new WaitForEndOfFrame();
RenderTexture.active = rt;
var screenSnapshot = new Texture2D( Screen.width, Screen.height, TextureFormat.RGBA32, false, false );
screenSnapshot.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0, false );
screenSnapshot.Apply();
byte[] bytes = screenSnapshot.EncodeToPNG();
string path = Application.dataPath + "/../" + (System.DateTime.Now).ToBinary().ToString() + ".png";
Debug.LogError("SavePath=" + path);
FileStream file = File.Open(path , FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(screenSnapshot);
cam.targetTexture = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment