欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Unity 一些小功能(屏幕画画,)

Unity 一些小功能(屏幕画画,)

2025/4/19 18:23:14 来源:https://blog.csdn.net/zaizai1007/article/details/147258160  浏览:    关键词:Unity 一些小功能(屏幕画画,)

利用 Line Renderer 实现屏幕画画并保存图片

// 当前正在绘制的 LineRendererprivate LineRenderer currentLineRenderer;// 用于保存所有笔触的列表private List<LineRenderer> allLineRenderers = new List<LineRenderer>();// 当前笔触顶点计数器private int vertexCount = 0;// 鼠标是否处于按下状态private bool mouseDown = false;// 用于展示生成图片的 UI Image(需要在 Inspector 中绑定)public Image displayImage;private Color currentColor = Color.black;public void ChangeColor(string colorStr){if(colorStr == "Red"){currentColor = Color.red;}else if(colorStr == "black"){currentColor = Color.black;}else if(colorStr == "blue"){currentColor = Color.blue;}}public void SavePicture(){StartCoroutine(CaptureAndSetSprite());}void Update(){// 鼠标左键按下时开始新的一笔if (Input.GetMouseButtonDown(0)){StartNewLine();mouseDown = true;}// 鼠标左键松开时结束当前绘制if (Input.GetMouseButtonUp(0)){mouseDown = false;}// 鼠标按下期间实时添加顶点if (mouseDown){// 将鼠标屏幕坐标转换为世界坐标// 此处 z 的值决定平面距离摄像机的距离(根据实际需求调整)Vector3 pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 3f);pos = Camera.main.ScreenToWorldPoint(pos);// 增加顶点到当前的 LineRenderercurrentLineRenderer.positionCount = vertexCount + 1;currentLineRenderer.SetPosition(vertexCount, pos);vertexCount++;}}/// <summary>/// 每次开始新的一笔时,创建一个新的 LineRenderer,保证之前的绘制不会被清除/// </summary>void StartNewLine(){// 新建一个 GameObject 并添加 LineRenderer 组件GameObject lineObj = new GameObject("LineStroke");// 将新生成的对象设为当前对象的子物体,便于管理lineObj.transform.parent = this.transform;currentLineRenderer = lineObj.AddComponent<LineRenderer>();// 设置基本属性(宽度、材质、颜色等),可根据需求调整currentLineRenderer.widthCurve = AnimationCurve.Constant(0, 1, 0.05f);currentLineRenderer.positionCount = 0;currentLineRenderer.material = new Material(Shader.Find("Sprites/Default"));currentLineRenderer.startColor = currentColor;currentLineRenderer.endColor = currentColor;// 添加到列表中便于管理后续可能的操作allLineRenderers.Add(currentLineRenderer);// 重置当前笔触顶点计数器vertexCount = 0;}/// <summary>/// 协程:在当前帧渲染结束后,捕获屏幕内容,/// 并将生成的图片转为 Sprite,然后赋给 UI Image 组件进行展示/// </summary>IEnumerator CaptureAndSetSprite(){// 等待这一帧结束,确保所有渲染都完成yield return new WaitForEndOfFrame();// 获取当前屏幕尺寸int width = Screen.width;int height = Screen.height;// 新建一个 Texture2D,用于存储截屏数据Texture2D texture = new Texture2D(width, height, TextureFormat.RGB24, false);// 读取屏幕像素数据texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);texture.Apply();// 创建 Sprite:Rect 表示截取的区域,锚点通常设为中心 (0.5, 0.5)Sprite newSprite = Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));// 将生成的 Sprite 赋给 UI Image 组件进行展示if (displayImage != null){displayImage.sprite = newSprite;}else{Debug.LogWarning("displayImage 没有绑定 UI Image 组件!");}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词