修改UGUI RawImage形状(在一个rawimage上显示N个颜色,两两颜色之间有过度)

效果图:
修改UGUI RawImage形状(在一个rawimage上显示N个颜色,两两颜色之间有过度)_第1张图片

将代码继承Graphic,然后重写OnPopulateMesh方法即可,具体代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class test : Graphic {
    /// 
    /// 分的块数
    /// 
    private int count = 5;
    /// 
    /// 每一块的颜色
    /// 
    public List c = new List();

    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().sizeDelta.x;
        float height = transform.GetComponent().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添加一个颜色

你可能感兴趣的:(unity)