1. 程式人生 > >修改UGUI RawImage形狀(在一個rawimage上顯示N個顏色,兩兩顏色之間有過度)

修改UGUI RawImage形狀(在一個rawimage上顯示N個顏色,兩兩顏色之間有過度)

效果圖:
這裡寫圖片描述

將程式碼繼承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新增一個顏色