Unity屏幕截图保存
截取任意分辨率下Canvas内任意位置任意大小的recttransform的内容。
代码
public IEnumerator SavePic(Canvas canvas, RectTransform target, string savePath)
{
yield return new WaitForEndOfFrame();
//Canvas的sizeDelta
Vector3 canvasSize = canvas.GetComponent<RectTransform>().sizeDelta;
//截取目标的左下角
Vector2 origin = new Vector2((target.localPosition.x + (canvasSize.x - target.rect.width) / 2f) * Screen.width / canvasSize.x,
(target.localPosition.y + (canvasSize.y - target.rect.height) / 2f) * Screen.height / canvasSize.y);
//截取目标的大小
Vector2 size = new Vector2(target.rect.width * Screen.width / canvasSize.x, target.rect.height * Screen.height / canvasSize.y);
//截取
Texture2D screenShot = new Texture2D((int) size.x, (int) size.y, TextureFormat.RGB24, true);
Rect position = new Rect(origin.x, origin.y, size.x, size.y);
screenShot.ReadPixels(position, 0, 0, true); //按照设定区域读取像素;注意是以左下角为原点读取
screenShot.Apply();
//保存
string filePath = savePath + ".jpg";
byte[] byt = screenShot.EncodeToPNG();
File.WriteAllBytes(filePath, byt);
System.Diagnostics.Process.Start(filePath);
}