当前位置:   article > 正文

Unity2022 UI Toolkit Vector Api绘图简介_2022版本的ui toolkit

2022版本的ui toolkit

首先在场景中创建UIDocument,如图:

其次在工程中创建UIDocument的Source Asset,如图:

这里我把这个Source Asset重新命名为VectorApiTest并把它指定给场景中的UIDocument。如图:

 

双击VectorApiTest文件进行编辑,首先选择VectorApiTest.uxml根对象,勾选Match Game View,如图:

然后添加一个可视元素,命名为Background,并设置尺寸,如图:

 

好了,开始写代码。创建一个继承VisualElement的类BezierConnect,脚本内容入下:

  1. using UnityEngine;
  2. using UnityEngine.UIElements;
  3. public class BezierConnet : VisualElement
  4. {
  5. Vector2 pStart;
  6. Vector2 pEnd;
  7. Color color;
  8. float width;
  9. public BezierConnet(Vector2 pStart, Vector2 pEnd, Color color, float width)
  10. {
  11. this.pStart = pStart;
  12. this.pEnd = pEnd;
  13. this.color = color;
  14. this.width = width;
  15. generateVisualContent += OnGenerateVisualContent;
  16. }
  17. void OnGenerateVisualContent(MeshGenerationContext mgc)
  18. {
  19. Painter2D painter2D = mgc.painter2D;
  20. painter2D.strokeColor = color;
  21. painter2D.lineWidth = width;
  22. painter2D.BeginPath();
  23. painter2D.MoveTo(pStart);
  24. float x = (pStart.x + pEnd.x) * 0.5f;
  25. Vector2 p1 = new Vector2(x, pStart.y);
  26. Vector2 p2 = new Vector2(x, pEnd.y);
  27. painter2D.BezierCurveTo(p1, p2, pEnd);
  28. painter2D.Stroke();
  29. }
  30. }

 再创建一个PaintTest类,脚本内容入下:

  1. using UnityEngine;
  2. using UnityEngine.UIElements;
  3. [RequireComponent(typeof(UIDocument))]
  4. public class PaintTest : MonoBehaviour
  5. {
  6. UIDocument doc;
  7. void Start()
  8. {
  9. doc = GetComponent<UIDocument>();
  10. VisualElement element = doc.rootVisualElement.Q("Background");
  11. element.Add(new BezierConnet(new Vector2(100, 100), new Vector2(200, 200), Color.red, 3));
  12. element.Add(new BezierConnet(new Vector2(200, 300), new Vector2(400, 200), Color.blue, 5));
  13. }
  14. }

这个脚本挂到场景中UIDocument那个物体上去,如图:

好了,运行起来看看吧。如果一切顺利,结果入下:

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/140752
推荐阅读
相关标签
  

闽ICP备14008679号