生成一张镜像图片扩展在原图片上,这样能使左右对称的图片只需要在资源中保存一半,节省了存储空间
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
[RequireComponent(typeof(Image))]
public class MyMirrorImage : BaseMeshEffect
{
List<UIVertex> vertexs = new List<UIVertex>();
public override void ModifyMesh(VertexHelper vh)
{
vertexs.Clear();
vh.GetUIVertexStream(vertexs);
ModifyVertices(vertexs);
vh.Clear();
vh.AddUIVertexTriangleStream(vertexs);
}
private void ModifyVertices(List<UIVertex> vertexs)
{
if (!IsActive() || vertexs.Count < 6)
{
return;
}
var image = GetComponent<Image>();
if (image.sprite == null)
return;
var startPos = vertexs[0].position;
var color = vertexs[0].color;
var endPos = vertexs[vertexs.Count - 2].position;
var tempVertexs = new List<UIVertex>();
for (int i = 0; i < vertexs.Count; i++) //全部向左缩小一半 并且拷贝一份顶点
{
var v = vertexs[i];
v.position.x = (v.position.x + startPos.x) / 2f;
vertexs[i] = v;
v.position.x += (endPos.x - startPos.x)/2f;
tempVertexs.Add(v);
}
//将拷贝的一份镜像翻转
{
//1和23交换
var v1 = tempVertexs[1];
var v2 = tempVertexs[2];
var v3 = tempVertexs[3];
v2.position = v1.position;
v1.position = v3.position;
v3.position = v2.position;
tempVertexs[1] = v1;
tempVertexs[2] = v2;
tempVertexs[3] = v3;
//4和05交换
v1 = tempVertexs[4];
v2 = tempVertexs[0];
v3 = tempVertexs[5];
v2.position = v1.position;
v1.position = v3.position;
v3.position = v2.position;
tempVertexs[4] = v1;
tempVertexs[0] = v2;
tempVertexs[5] = v3;
}
vertexs.AddRange(tempVertexs);
}
}