unity在低版本(4.x)中实现自定义形状的图片

如果图片想实现自定义图片,一般要重写OnPopulateMesh方法来用三角形拼出来一个图片。想要看具体怎么实现,请看这个大佬写的。
https://blog.csdn.net/wangjiangrong/article/details/107918646

这个方法是在unity5.x版本之后才出现,4.x没有这个方法,你接手的项目又是这种超级老的版本怎么办,你可以用以前提供的一个接口OnFillVBO来实现,具体用法差不多,只是这个方法是4个顶点的图片来绘制的,而不是现在的三角形绘制。具体请看实例:

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


[ExecuteInEditMode]
public class SimpleImage : Graphic
{
         

    protected override void OnFillVBO(List<UIVertex> vbo)
    {
     
        Vector2 corner1 = Vector2.zero;
        Vector2 corner2 = Vector2.zero;

        corner1.x = 0f;
        corner1.y = 0f;
        corner2.x = 1f;
        corner2.y = 1f;

        corner1.x -= rectTransform.pivot.x;
        corner1.y -= rectTransform.pivot.y;
        corner2.x -= rectTransform.pivot.x;
        corner2.y -= rectTransform.pivot.y;

        corner1.x *= rectTransform.rect.width;
        corner1.y *= rectTransform.rect.height;
        corner2.x *= rectTransform.rect.width;
        corner2.y *= rectTransform.rect.height;

        //cor1: -160,-103,      cor2:160,103
        //Debug.Log("cor1: " + corner1 + " , cor2: " + corner2);
        Vector2[] points = GetPoints();

        vbo.Clear();        

        UIVertex vert = UIVertex.simpleVert;
        vert.position = new Vector2(corner1.x, corner1.y);
        vert.position = points[0];
        vert.color = color;
        vert.uv0 = Vector2.zero;
        vert.uv1 = Vector2.one;
        vbo.Add(vert);

        //vert.position = new Vector2(corner1.x, corner2.y);
        vert.position = new Vector2(0, corner2.y);
        vert.position = points[1];
        vert.color = color;
        vbo.Add(vert);

        //vert.position = new Vector2(corner2.x, corner2.y);
        vert.position = new Vector2(0, corner2.y);
        vert.position = points[2];
        vert.color = color;
        vbo.Add(vert);

        //vert.position = new Vector2(corner2.x, corner1.y);
        vert.position = new Vector2(corner2.x, corner1.y);
        vert.position = points[3];
        vert.color = color;
        vbo.Add(vert);
    }



    Vector2[] GetPoints()
    {
     
        Vector2[] temp = new Vector2[4];
        //Transform[] childPos = new Transform[4];
        if(transform.childCount<4)
        {
     
            temp[0] = new Vector2(-160, -103);
            temp[1] = new Vector2(0, 103);
            temp[2] = new Vector2(0, 103);
            temp[3] = new Vector2(160, 103);

            return temp;
        }

        for(int i=0;i<transform.childCount;++i)
        {
                 
            if(transform.GetChild(i).name.Contains("Image"))
            {
     
                continue;
            }
            temp[i] = transform.GetChild(i).localPosition;
        }

        //Debug.Log("get vectors count: " + temp.Length);
        return temp;
    }


}
注意,OnFillVBO中至少要有4个点才可以显示图片。渲染时顺时针开始的。第一个是左下角,第二个是左上角,第三个点事右上角,第四个点是右下角。默认的原点是图片的中心点。

你可能感兴趣的:(Unity)