//水平翻转
Texture2D HorizontalFlipTexture(Texture2D texture)
{
//得到图片的宽高
int width = texture.width;
int height = texture.height;
Texture2D flipTexture = new Texture2D(width, height);
for (int i = 0; i < width; i++)
{
flipTexture.SetPixels(i, 0, 1, height, texture.GetPixels(width - i - 1, 0, 1, height));
}
flipTexture.Apply();
return flipTexture;
}
// 垂直翻转
Texture2D VerticalFlipTexture(Texture2D texture)
{
//得到图片的宽高
int width = texture.width;
int height = texture.height;
Texture2D flipTexture = new Texture2D(width, height);
for (int i = 0; i < height; i++)
{
flipTexture.SetPixels(0, i, width, 1, texture.GetPixels(0, height - i - 1, width, 1));
}
flipTexture.Apply();
return flipTexture;
}
GetPixel和SetPixel,GetPixel用来获取坐标为(x,y)的像素点的颜色,即参数为int x和int y,返回值为Color;SetPixel则用来设置新的像素点,参数为int x、int y及Color。一张2D Texture由width*height个像素点组成,想象一张网格图,每个网格对应一个像素点,则每个像素的横坐标在[0,width - 1]内,纵坐标在[0,height - 1]内。假设我们要将图片顺时针旋转90°,由于Unity中的坐标原点在图的左下角,故一个坐标为(x,y)的像素点旋转90°后的坐标变为了(y,width - 1 - x),对每个像素点进行这样的坐标变换就可实现图片的旋转了。具体代码如下:
public class TextureRotate
{
Texture2D texture = new Texture2D(300, 400);
int width = texture.width; //图片原本的宽度
int height = texture.height; //图片原本的高度
Texture2D newTexture = new Texture2D(height,width); //实例化一个新的texture,高度是原来的宽度,宽度是原来的高度
public Texture2D rotate()
{
for (int i = 0; i < width - 1; i++) {
for (int j = 0; j < height - 1; j++) {
Color color = texture.GetPixel(i,j);
newTexture.SetPixel(j, width - 1 - i, color);
}
}
newTexture.Apply();
return newTexture;
}
}