using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MeshImage : Image { private Vector2[] pos; private Vector2[] uvs; public int rotatePointIndex; [SerializeField] private bool isErrorReset; public void SetPos(Vector2[] pos, bool referesh) { this.pos = pos; this.uvs = SetUvs(pos); if (referesh) { SetAllDirty(); } } public void SetSize(float width, float height, bool adaptPointToSize) { rectTransform.sizeDelta = new Vector2(width, height); if (adaptPointToSize) { float minW = 9999; float minH = 9999; float maxW = -1; float maxH = -1; foreach (var po in pos) { if (po.x < minW) { minW = po.x; } if (po.x > maxW) { maxW = po.x; } if (po.y < minH) { minH = po.y; } if (po.y > maxH) { maxH = po.y; } } float w = maxW - minW; float h = maxH - minH; float sw = w / width; float sh = h / height; float s = sw > sh ? sw : sh; for (int i = 0; i < pos.Length; i++) { pos[i] /= s; } SetPos(pos, true); } } public void SetRotatePointIndex(int index) { rotatePointIndex = index; } public Vector2[] GetPos() { return pos; } private Vector2[] SetUvs(Vector2[] tempPos) { Vector2[] tempUvs = new Vector2[tempPos.Length]; for (int i = 0; i < tempPos.Length; i++) { tempUvs[i] = new Vector2(tempPos[i].x / rectTransform.rect.width + 0.5f, tempPos[i].y / rectTransform.rect.height + 0.5f); } return tempUvs; } protected override void OnPopulateMesh(VertexHelper vh) { Vector2[] tempPos = pos; Vector2[] tempUvs = uvs; if (tempPos == null) { base.OnPopulateMesh(vh); return; } Color32 color32 = color; vh.Clear(); try { for (int i = 0; i < tempPos.Length; i++) { vh.AddVert(tempPos[i], color32, tempUvs[i]); } Triangulator triangular = new Triangulator(tempPos); //计算三角面的类 int[] indices = triangular.Triangulate(); //得到三角面 for (int i = 0; i < indices.Length - 2; i += 3) { vh.AddTriangle(indices[i], indices[i + 1], indices[i + 2]); } } catch (Exception e) { Debug.LogError(e.ToString()); base.OnPopulateMesh(vh); } } }