程序丨以五边形为例,使用UGUI绘制多边形雷达图

 

内含工程地址。...

使用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写的是些什么。

///

///   Callback function when a UI element needs to generate vertices.

///

/// Mesh to populate with UI data.

/// VertexHelper utility.

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一下;目前实现的功能是可以在以一张多边形为背景, 在上面通过设置子雷达图的所占的比例来显示多个多边形。

----------------------
今日推荐
10月资料包、资料库下载
聊聊游戏引擎的定时器实现
如何从零开始创建一个游戏团队?
实时渲染的圣经!《RTR3》全书知识点总览
添加小编微信,可享双重福利
1.加入GAD程序猿交流基地
获取行业干货资讯,观看大牛分享直播
2.领取60G独家程序资料,地址在小编朋友圈
包括腾讯内部分享、文章教程、视频教程等全套资料
 
↓长按添加小编GAD苏苏↓


    关注 Gad腾讯游戏开发者平台


微信扫一扫关注公众号

0 个评论

要回复文章请先登录注册