Unity使用Aspose.Words创建表格和UI截图一起插入到Word中并保存到本地的一种解决方案_unity word-CSDN博客
参考以上文章,以下为自己记录。
1.将以下代码挂在到节点上
2.将要截取的节点拖入
/// <summary>
/// 截图的UI
/// </summary>
public RectTransform ScreenShotUI;
//保存的图片路径
string picturePath;
/// <summary>
/// 点击开始截图方法
/// </summary>
public void ScreenShotClick()
{
//图片路径
picturePath = Application.dataPath + "/../data/Word/picture.png";
IEnumerator coroutine = ScreenShot(ScreenShotUI, picturePath);
StartCoroutine(coroutine);
}
/// <summary>
/// 异步读取UI像素转为字节流数据并保存
/// </summary>
/// <param name="ScreenShotUI"></param>
/// <param name="mFileName">保存截图的路径名</param>
/// <returns></returns>
public IEnumerator ScreenShot(RectTransform ScreenShotUI, string mFileName)
{
//等待帧画面渲染结束
yield return new WaitForEndOfFrame();
int uiWidth = (int)(ScreenShotUI.rect.width);
int uiHeight = (int)(ScreenShotUI.rect.height);
Texture2D tex = new Texture2D(uiWidth, uiHeight, TextureFormat.RGB24, false);
//左下角为原点(0, 0)
float uiLeftX = ScreenShotUI.transform.position.x + ScreenShotUI.rect.xMin;
float uiLeftY = ScreenShotUI.transform.position.y + ScreenShotUI.rect.yMin;
//从屏幕读取像素, leftBtmX/leftBtnY 是读取的初始位置,width、height是读取像素的宽度和高度
//可以根据需求更改宽高
tex.ReadPixels(new Rect(uiLeftX, uiLeftY, uiWidth, uiHeight), 0, 0);
//执行读取操作
tex.Apply();
//将纹理图片转为字节流数据
byte[] bytes = tex.EncodeToPNG();
//将字节流数据保存到本地
System.IO.File.WriteAllBytes(mFileName, bytes);
}