记录一下,方便后面取用
private Texture2D TextureJuXingToFangXing(Texture2D tex)
{
if (tex.width == tex.height) return tex;
int max = tex.height > tex.width ? tex.height : tex.width;
int min = tex.height > tex.width ? tex.width : tex.height;
int chaZhi = max - min;
// 这里我也不知道为什么要用false
Texture2D newTex = new Texture2D(max, max, tex.format, false);
Color[] oldColors = tex.GetPixels();
// 取这个透明度不知道有没有用
float a = oldColors[0].a;
Color c = new Color(1, 1, 1, a);
List<Color> listColor = new List<Color>();
// 假如图片10*10 左下为(0,0) 右上为(9,9)
// Texture2d 的颜色排列方式 ( tex.GetPixels() 颜色数组的排列方式 ):
// (0,0) (0,1) ... (0,9) (1,0) ...(9,8) (9,9)
// 当原图片 宽度大于高度 需要在原图上面和下面补充颜色
// 在 颜色数组前面添加 原图下面的颜色数量
// 在 数组后面添加上面的颜色数量即可
if (tex.width > tex.height)
{
// 如果差值是奇数,默认下边和右边 多1
int downPx = chaZhi / 2 + chaZhi % 2;
int topPx = chaZhi - downPx;
for (int i = 0; i < downPx * tex.width; i++)
{
listColor.Add(c);
}
for (int i = 0; i < oldColors.Length; i++)
{
listColor.Add(oldColors[i]);
}
for (int i = 0; i < topPx * tex.width; i++)
{
listColor.Add(c);
}
}
// 当原图片 高度大于宽度 需要在原图左右补充颜色
// 按照排列方式 把图片像素颜色 按照行来划分
// 每一行的颜色为 左边添加的颜色 原图这一行的颜色 右边添加的颜色
else
{
int rightPx = chaZhi / 2 + chaZhi % 2;
int leftPx = chaZhi - rightPx;
for (int i = 0; i < max; i++)
{
for (int j = 0; j < leftPx; j++)
{
listColor.Add(c);
}
for (int j = 0; j < tex.width; j++)
{
listColor.Add(oldColors[i * tex.width + j]);
}
for (int j = 0; j < rightPx; j++)
{
listColor.Add(c);
}
}
}
newTex.SetPixels(listColor.ToArray());
newTex.Apply();
return newTex;
}