您的位置:首页 > 移动开发 > Unity3D

Unity干中学——如何实现游戏截图?

2014-10-19 22:43 89 查看
using UnityEngine;
using System.Collections;
using System.IO;

public class ScreenShot : MonoBehaviour
{
// Use this for initialization
void Update()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.L))
{
StartCoroutine(CaptureScreen());
}

}

public IEnumerator CaptureScreen()
{
// 渲染完成之后在读取屏幕缓冲
yield return new WaitForEndOfFrame();
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);//要保存图片的大小
//截取的区域
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
//把图片数据转换为byte数组
byte[] buffer = tex.EncodeToPNG();
Destroy(tex);
//然后保存为图片
File.WriteAllBytes(Application.persistentDataPath + "/" + System.DateTime.Now.ToFileTime() + ".png", buffer);
}
}

上面的代码参考了Unity的脚本手册,实现同时按下LeftAlt和L键进行屏幕截图。下一篇文章我将实现通知中心的功能,将截图完成的信息显示出来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: