unity字节转贴图贴图旋转
时间: 2023-11-13 09:03:55 浏览: 158
一键旋转、翻转贴图(Unity内).zip
您可以使用以下代码将字节数据转换为纹理,并在Unity中旋转它:
```csharp
public Texture2D BytesToTexture(byte[] bytes, int width, int height)
{
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes);
return texture;
}
public Texture2D RotateTexture(Texture2D originalTexture, float angle)
{
int width = originalTexture.width;
int height = originalTexture.height;
RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
Graphics.Blit(originalTexture, renderTexture);
RenderTexture.active = renderTexture;
Texture2D rotatedTexture = new Texture2D(width, height);
rotatedTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
rotatedTexture.Apply();
RenderTexture.active = null;
RenderTexture.ReleaseTemporary(renderTexture);
return rotatedTexture.Rotate(angle);
}
public Texture2D Rotate(this Texture2D originalTexture, float angle)
{
Texture2D rotatedTexture = new Texture2D(originalTexture.width, originalTexture.height);
int x, y;
float x1, y1;
float[,] values = new float[originalTexture.width, originalTexture.height];
float radianAngle = angle * Mathf.Deg2Rad;
float sin = Mathf.Sin(radianAngle);
float cos = Mathf.Cos(radianAngle);
for (y = 0; y < originalTexture.height; y++)
{
for (x = 0; x < originalTexture.width; x++)
{
x1 = ((x - originalTexture.width / 2) * cos) - ((y - originalTexture.height / 2) * sin) + originalTexture.width / 2;
y1 = ((x - originalTexture.width / 2) * sin) + ((y - originalTexture.height / 2) * cos) + originalTexture.height / 2;
if (x1 > 0 && x1 < originalTexture.width && y1 > 0 && y1 < originalTexture.height)
{
values[x, y] = originalTexture.GetPixelBilinear(x1 / originalTexture.width, y1 / originalTexture.height).grayscale;
}
}
}
for (y = 0; y < originalTexture.height; y++)
{
for (x = 0; x < originalTexture.width; x++)
{
rotatedTexture.SetPixel(x, y, new Color(values[x, y], values[x, y], values[x, y], 1));
}
}
rotatedTexture.Apply();
return rotatedTexture;
}
```
使用示例:
```csharp
byte[] bytes = File.ReadAllBytes("path/to/texture.png");
Texture2D texture = BytesToTexture(bytes, 512, 512);
Texture2D rotatedTexture = RotateTexture(texture, 90f);
```
此示例将读取512x512像素的PNG文件,并将其旋转90度。
阅读全文