两个注意点
- 等待当前帧完成之后再去截屏,不然接取的屏幕不正常。
- 图片的质量问题 RenderTexture格式和Texture格式。
using UnityEngine;
using System.Collections;
public class ZWGShotScreen : MonoBehaviour {
[ContextMenu("ShotScreen")]
void ShotScreen()
{
StartCoroutine(ShotScreenCore());
}
IEnumerator ShotScreenCore()
{
yield return new WaitForEndOfFrame();
// 屏幕大小
int width = Screen.width;
int height = Screen.height;
// RT gpu内存中 并且会关联一个FBO 默认的FBO即屏幕显示的画面信息
RenderTexture rt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
Camera.main.targetTexture = rt;
Camera.main.Render();
// 设置当前FBO为可读 接下来可以通过接口获取激活的FBO信息
RenderTexture.active = rt;
// texture cpu 内存中
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24,false);
tex.ReadPixels(new Rect(0,0, width, height),0,0);
tex.Apply();
// 清理
Camera.main.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
// 保存图片
byte[] bytes = tex.EncodeToPNG();
string path = Application.streamingAssetsPath + "/custom_shot_screen.png";
System.IO.File.WriteAllBytes(path,bytes);
}
}