CustomBorder.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Sprites;
  4. [RequireComponent(typeof(CanvasRenderer))]
  5. public class CustomBorder : MaskableGraphic
  6. {
  7. // 边框的厚度
  8. public float borderThickness = 5.0f;
  9. // 边框的颜色
  10. public Color borderColor = Color.black;
  11. protected override void Start()
  12. {
  13. base.Start();
  14. // 确保边框颜色使用图像模式
  15. //colorGradient = new ColorBlock { normal = borderColor };
  16. }
  17. protected override void OnPopulateMesh(VertexHelper vh)
  18. {
  19. vh.Clear();
  20. Rect rect = rectTransform.rect;
  21. Vector2 bottomLeft = new Vector2(rect.x, rect.y);
  22. Vector2 topRight = new Vector2(rect.xMax, rect.yMax);
  23. // 边框的四个顶点
  24. var v1 = new Vector2(bottomLeft.x, bottomLeft.y - borderThickness);
  25. var v2 = new Vector2(bottomLeft.x, topRight.y + borderThickness);
  26. var v3 = new Vector2(topRight.x + borderThickness, topRight.y);
  27. var v4 = new Vector2(topRight.x - borderThickness, bottomLeft.y);
  28. vh.AddUIVertexQuad(GetQuad(v1, v2, v3, v4));
  29. }
  30. private UIVertex[] GetQuad(Vector2 v1, Vector2 v2, Vector2 v3, Vector2 v4)
  31. {
  32. UIVertex[] vertexs = new UIVertex[4];
  33. vertexs[0] = new UIVertex();
  34. vertexs[0].position = v1;
  35. vertexs[1] = new UIVertex();
  36. vertexs[1].position = v2;
  37. vertexs[2] = new UIVertex();
  38. vertexs[2].position = v3;
  39. vertexs[3] = new UIVertex();
  40. vertexs[3].position = v4;
  41. return vertexs;
  42. }
  43. }