60 lines
1.8 KiB
C#
60 lines
1.8 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
[RequireComponent(typeof(Image))]
|
|
public class RoundedRectImage : MonoBehaviour
|
|
{
|
|
public float cornerRadius = 10f;
|
|
|
|
private Image image;
|
|
|
|
void Start()
|
|
{
|
|
image = GetComponent<Image>();
|
|
UpdateMesh();
|
|
}
|
|
|
|
void UpdateMesh()
|
|
{
|
|
Rect rect = image.rectTransform.rect;
|
|
Vector2 size = rect.size;
|
|
Vector2 center = rect.center;
|
|
|
|
UIVertex[] vertices = new UIVertex[4];
|
|
Vector2[] uv = new Vector2[4];
|
|
Vector2[] positions = new Vector2[4];
|
|
|
|
positions[0] = new Vector2(-size.x / 2f, -size.y / 2f);
|
|
positions[1] = new Vector2(size.x / 2f, -size.y / 2f);
|
|
positions[2] = new Vector2(size.x / 2f, size.y / 2f);
|
|
positions[3] = new Vector2(-size.x / 2f, size.y / 2f);
|
|
|
|
uv[0] = new Vector2(0f, 0f);
|
|
uv[1] = new Vector2(1f, 0f);
|
|
uv[2] = new Vector2(1f, 1f);
|
|
uv[3] = new Vector2(0f, 1f);
|
|
|
|
for (int i = 0; i < 4; i++)
|
|
{
|
|
vertices[i] = UIVertex.simpleVert;
|
|
vertices[i].position = positions[i];
|
|
vertices[i].uv0 = uv[i];
|
|
}
|
|
|
|
// 处理圆角
|
|
float halfRadius = cornerRadius / 2f;
|
|
vertices[0].position += new Vector3(halfRadius, halfRadius, 0f);
|
|
vertices[1].position += new Vector3(-halfRadius, halfRadius, 0f);
|
|
vertices[2].position += new Vector3(-halfRadius, -halfRadius, 0f);
|
|
vertices[3].position += new Vector3(halfRadius, -halfRadius, 0f);
|
|
|
|
int[] triangles = new int[6] { 0, 1, 2, 2, 3, 0 };
|
|
|
|
Mesh mesh = new Mesh();
|
|
mesh.vertices = System.Array.ConvertAll(vertices, v => (Vector3)v.position);
|
|
mesh.uv = uv;
|
|
mesh.triangles = triangles;
|
|
|
|
image.canvasRenderer.SetMesh(mesh);
|
|
}
|
|
} |