基于UGUI的多边形雷达图

发表于2017-11-02
评论2 7.7k浏览
使用UGUI绘制多边形(这里以五边形为例子), 首先我们先看一下UGUI里的绘制一张图片需要实现的一个函数
protected override void OnPopulateMesh(VertexHelper toFill)
    {
      if ((UnityEngine.Object) this.activeSprite == (UnityEngine.Object) null)
      {
        base.OnPopulateMesh(toFill);
      }
      else
      {
        switch (this.type)
        {
          case Image.Type.Simple:
            this.GenerateSimpleSprite(toFill, this.m_PreserveAspect);
            break;
          case Image.Type.Sliced:
            this.GenerateSlicedSprite(toFill);
            break;
          case Image.Type.Tiled:
            this.GenerateTiledSprite(toFill);
            break;
          case Image.Type.Filled:
            this.GenerateFilledSprite(toFill, this.m_PreserveAspect);
            break;
        }
      }
    }

这个函数是由Image重写了MaskGraphic所继承的Graphic所提供的一个虚函数(有点绕!!@_@)
我们再来看一下Graphic内部的OnPopulateMesh写的是些什么
/// <summary>
    ///   <para>Callback function when a UI element needs to generate vertices.</para>
    /// </summary>
    /// <param name="m">Mesh to populate with UI data.</param>
    /// <param name="vh">VertexHelper utility.</param>
    protected virtual void OnPopulateMesh(VertexHelper vh)
    {
      Rect pixelAdjustedRect = this.GetPixelAdjustedRect();
      Vector4 vector4 = new Vector4(pixelAdjustedRect.x, pixelAdjustedRect.y, pixelAdjustedRect.x   pixelAdjustedRect.width, pixelAdjustedRect.y   pixelAdjustedRect.height);
      Color32 color = (Color32) this.color;
      vh.Clear();
      vh.AddVert(new Vector3(vector4.x, vector4.y), color, new Vector2(0.0f, 0.0f));
      vh.AddVert(new Vector3(vector4.x, vector4.w), color, new Vector2(0.0f, 1f));
      vh.AddVert(new Vector3(vector4.z, vector4.w), color, new Vector2(1f, 1f));
      vh.AddVert(new Vector3(vector4.z, vector4.y), color, new Vector2(1f, 0.0f));
      vh.AddTriangle(0, 1, 2);
      vh.AddTriangle(2, 3, 0);
    }

这里的VerexHelper是一个工具类, 用来存储了UI生成一个mesh所需要的顶点数据;因为生成一个image需要四个顶点, 所以, 这里的用了verctor4作为临时变量, 根据image的pixelAdjustedRect的大小和位置, 来计算出image的四个顶点的位置
// pixelAjustedRect : Returns a pixel perfect Rect closest to the Graphic RectTransform

那么这个时候, 我们就拿到了生成一个mesh所需要的数据了, 所以, 想要自己绘制一个多边形, 其实可以仿照这种方式

我们可以自定义一个类继承与Graphic, 然后通过重写内部的OnPopulateMesh虚函数, 往里面塞进去我们计算好的数据;
这里要注意的是, 顶点vertex, 以及顶点所组成的三角形triangle, 然后uv坐标都是需要围绕你所定义的顶点的顺序来计算的, 可以参看下面我画的示意图
顶点位置示意图

2 | 7
|
|
3 | 6
|
|
0 1 | 4 5

UV坐标示意图

(0.0,1)-----------(1, 1)
| |
| |
| |
| |
| |
| |
(0.0,0.0)---------(1.0,0.0)
三角形分布示意图

x, w(1)-----------z, w(2)
| |
| |
| |
| |
| |
| |
x, y(0)-----------z, y(3)

五边形顶点位置顺序示意图

3


4 2



0 1

这种方式有个缺点在于, 如果是直接绘制了多边形的话, 那么就不好直接在source image上通过拖拽一张图片来达到替换背景的效果了, 不过应该还是有其他的方法来实现的;

最后附上工程地址: https://github.com/Zhuangdum/RadarChart  有兴趣的朋友不妨点星Fork一下目前实现的功能是可以在以一张多边形为背景, 在上面通过设置子雷达图的所占的比例来显示多个多边形;
有什么需要完善或者建议欢迎和大家和我交流

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引