3d部分使用MeshRenderer来渲染,ugui的使用CanvasRenderer来进行渲染。把顶点,材质,贴图设置给CanvasRenderer,就能渲染出来了。
下面的代码,我们直接使用CanvasRenderer来进行渲染,等同于Graphic渲染部分的核心代码。
using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(CanvasRenderer))] public class TestCanvasRenderer : MonoBehaviour { [SerializeField] public Texture m_Texture; private VertexHelper m_VertexHelper; void Start() { UpdateRenderer(); } void UpdateRenderer() { var canvasRenderer = GetComponent<CanvasRenderer>(); canvasRenderer.Clear(); var vh = new VertexHelper(); //设置顶点 var mesh = new Mesh(); PopulateMesh(vh); vh.FillMesh(mesh); canvasRenderer.SetMesh(mesh); //设置材质和贴图 canvasRenderer.materialCount = 1; var myMat = Canvas.GetDefaultCanvasMaterial(); canvasRenderer.SetMaterial(myMat, 0); var myTexture = (null == m_Texture) ? Texture2D.whiteTexture : m_Texture; canvasRenderer.SetTexture(myTexture); } void PopulateMesh(VertexHelper vh) { Color32 vertColor = Color.white; float width = 150; float height = 100; //这边添加一个四边形 vh.AddVert(new Vector3(0, 0), vertColor, new Vector2(0f, 0f)); //左下 vh.AddVert(new Vector3(0, height), vertColor, new Vector2(0f, 1f)); //左上 vh.AddVert(new Vector3(width, height), vertColor, new Vector2(1f, 1f)); //右上 vh.AddVert(new Vector3(width, 0), vertColor, new Vector2(1f, 0f)); //右下 //顺时针 vh.AddTriangle(0, 1, 2); vh.AddTriangle(2, 3, 0); } #if UNITY_EDITOR protected void OnValidate() { UpdateRenderer(); } #endif }
图片偏右上角,主要是因为顶点(0, 0)是相对RectTransform的pivot的,此时pivot在(0.5, 0.5)中心位置,所以图片的左下角是在中心位置的。
标签:Graphic,canvasRenderer,vh,渲染,源码,var,new,ugui,vertColor From: https://www.cnblogs.com/sailJs/p/17583020.html