效果图:
将代码继承Graphic,然后重写OnPopulateMesh方法即可,具体代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : Graphic {
/// <summary>
/// 分的块数
/// </summary>
private int count = 5;
/// <summary>
/// 每一块的颜色
/// </summary>
public List<Color> c = new List<Color>();
private int index = 0;
protected override void Start()
{
c.Clear();
for (int i = 0; i < count + 1; i++) {
c.Add(Color.white);
}
}
private void Update()
{
if (Input.GetMouseButtonDown(0)) {
c[index] = new Color(Random.Range(0, 255) / 255.0f, Random.Range(0, 255) / 255.0f, Random.Range(0, 255) / 255.0f, 1);
index++;
if (index >= count + 1) {
index = 0;
}
}
SetAllDirty();//刷新界面
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
//计算宽高,和每一块的宽高
float width = transform.GetComponent<RectTransform>().sizeDelta.x;
float height = transform.GetComponent<RectTransform>().sizeDelta.y;
float singleWidth = width / count;
float singleHeight = height * 0.5f;
//
// upLeft upRight
// -----------------------------
// | | | |
// -----------------------------
// downLeft downRight
Vector2 upLeft = new Vector2(-width * 0.5f, singleHeight);
Vector2 downLeft = new Vector2(-width * 0.5f, -singleHeight);
Vector2 upRight = new Vector2(upLeft.x + singleWidth, singleHeight);
Vector2 downRight = new Vector2(downLeft.x + singleWidth, -singleHeight);
for (int i = 0; i < count; i++) {
UIVertex first = GetUIVertex(upLeft, c[i]);
UIVertex second = GetUIVertex(downLeft, c[i]);
UIVertex third = GetUIVertex(downRight, c[i + 1]);
UIVertex four = GetUIVertex(upRight, c[i + 1]);
vh.AddUIVertexQuad(new UIVertex[] {first,second,third,four });
upLeft = upRight;
downLeft = downRight;
upRight = upRight + new Vector2(singleWidth, 0);
downRight = downRight + new Vector2(singleWidth, 0);
}
for (int i = 0; i < vh.currentVertCount; i+=4) {
vh.AddTriangle(i + 0, i + 3, i + 2);
vh.AddTriangle(i + 0, i + 2, i + 1);
}
}
private UIVertex GetUIVertex(Vector2 point, Color color0) {
UIVertex vertex = new UIVertex
{
position = point,
color = color0,
};
return vertex;
}
}
运行状态下,点击一下鼠标RawImage添加一个颜色