最近有个项目涉及到截屏,然后我就整理下资料,留作以后用。
定义空格键来执行截屏事件;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("截屏");
Camera camera = GameObject.Find("Main Camera").gameObject.GetComponent<Camera>();
int ratio = 2;
Rect rect = new Rect(0, 0, (int)Screen.width / ratio, (int)Screen.height / ratio);//图片大小取决于ratio的大小
Texture2D aa = ScreenShot(camera, rect);
}
}
根据相机截屏,并保存图片
public Texture2D ScreenShot(Camera camera, Rect rect)
{
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
camera.targetTexture = rt;
camera.Render();
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
camera.targetTexture = null;
RenderTexture.active = null;
GameObject.Destroy(rt);
byte[] bytes = screenShot.EncodeToPNG();
string filename = Application.dataPath + "/Resources/ScreenShot/screenshot.png";//存放路径
System.IO.File.WriteAllBytes(filename, bytes);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();//刷新,这步很关键,否则后面调用图片时没有。
#endif
Invoke("CreateImage", 0.5f);
return screenShot;
}
创建Image对象,显示截图
void CreateImage()
{
GameObject go = GameObject.Find("Canvas/Image").gameObject;//先创建一个空物体
GameObject Im = new GameObject();
Im.name = "jieping";
Im.transform.SetParent(go.transform, false);
Im.AddComponent<Image>();//添加Image属性
Im.GetComponent<Image>().sprite = Resources.Load<Sprite>("ScreenShot/screenshot");//将图片赋到Image上
Im.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width, Screen.height);//定义图片最初显示尺寸
Vector2 v2 = new Vector2((float)(113.8 * 7), (float)(64.2 * 7));//定义图片缩放后尺寸
StartCoroutine(sizeDelta(Im, v2));
}
动态缩放图片,停留一定时间后隐藏对象。
int RemainCount = 0;
IEnumerator sizeDelta(GameObject go, Vector2 endSize)
{
while (true)
{
yield return new WaitForSeconds(0.001f);
if (go.GetComponent<RectTransform>().sizeDelta != endSize)
{
go.GetComponent<RectTransform>().sizeDelta = Vector2.MoveTowards(go.GetComponent<RectTransform>().sizeDelta, endSize, 1000 * Time.deltaTime);
}
else
{
if (RemainCount == 300)//停留150帧后隐藏图片
{
go.SetActive(false);
RemainCount = 0;
}
else
{
go.GetComponent<RectTransform>().sizeDelta = endSize;
RemainCount++;
}
}
}
}