指定控件大小截图 ,图片像素 会根据屏幕像素的变化产生变化
public IEnumerator Capsture(RectTransform rectT, string filePath = "", OnConfirm onConfirm = null)
{
yield return new WaitForEndOfFrame();
// 计算自适应屏幕宽高
Vector3[] worldcorners = new Vector3[4];
//获取 UI四个点的世界坐标
rectT.GetWorldCorners(worldcorners);
//再次转换为屏幕坐标
for (int i = 0; i < worldcorners.Length; i++)
{
worldcorners[i] = Camera.main.WorldToScreenPoint(worldcorners[i]);
}
//计算宽高查值
Vector2 Difference = worldcorners[0] - worldcorners[2];
float width = Mathf.Abs(Difference.x);
float height = Mathf.Abs(Difference.y);
//创建纹理(纹理贴图的大小和截屏的大小相同)
Texture2D tex = new Texture2D((int)width, (int)height);
//读取像素点
Vector2 leftPos;
leftPos = Camera.main.WorldToScreenPoint(rectT.transform.position);
Rect position = new Rect(leftPos.x, leftPos.y, width, height);
tex.ReadPixels(position, 0, 0);
//将像素点应用到纹理上,绘制图片
tex.Apply();
//将图片装换成jpg的二进制格式,保存在byte数组中(计算机是以二进制的方式存储数据)
byte[] result = tex.EncodeToPNG();
//文件夹(如果StreamAssets文件夹不存在,在Assets文件下创建该文件夹)
if (filePath != "")
{
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
filePath += "/" + "screenshot.png";
//将截屏图片存储到本地
Debug.Log("filePath:" + filePath);
File.WriteAllBytes(filePath, result);
}
if (rawImage != null)
rawImage.texture = tex;
onConfirm?.Invoke();
}