方法1
不能指定截图尺寸
官方API
ScreenCapture.CaptureScreenshot(Application.dataPath + “/Resources/1.png”); //指定路径和后缀名 jpg或者png
方法2
指定截图尺寸
注意:矩形局域不能超过当前画面显示尺寸
Rect 确定截取区域的大小
ReadPixels 将屏幕像素读取到纹理中 参数1 矩形区域的左下角为原点 因此可以修改矩形的中心点 调整截图位置 参数2 参数3 将截图进行偏移
EncodeToPNG 纹理编码为 PNG 格式
File.WriteAllBytes 创建一个新文件,在其中写入指定的字节数组,然后关闭该文件。 如果目标文件已存在,则覆盖该文件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Photo : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Rect rec = new Rect(0, 0, Screen.width / 2, Screen.height / 2);
rec.center = new Vector2(Screen.width / 4, Screen.height / 4 * 3);//屏幕一分为四 左上侧部分
StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/A.Png"));
rec.center = new Vector2(Screen.width / 4 * 3, Screen.height / 4 * 3);//屏幕一分为四 右上侧部分
StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/B.Png"));
rec.center = new Vector2(Screen.width / 4, Screen.height / 4);//屏幕一分为四 左下侧部分
StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/C.Png"));
rec.center = new Vector2(Screen.width / 4 * 3, Screen.height / 4);//屏幕一分为四 右下侧部分
StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/D.Png"));
rec.center = new Vector2(Screen.width / 2, Screen.height / 2);//屏幕中心区域
StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/E.Png"));
rec = new Rect(0,0,Screen.width,Screen.height);
StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/F.Png"));//整体
}
}
IEnumerator IBegin(Rect rect, string url)
{
yield return new WaitForEndOfFrame();
CaptureScreenshot(rect, url);
}
private void CaptureScreenshot(Rect rect, string url)
{
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
byte[] bytes = screenShot.EncodeToPNG();
System.IO.File.WriteAllBytes(url, bytes);
}
}