EditorTool3D/Assets/ZXL/Scripts/Helper/TextureHelper.cs

71 lines
2.5 KiB
C#

using UnityEngine;
namespace ZXL.Helper
{
public static class TextureHelper
{
/// <summary>
/// 精灵图片转纹理
/// </summary>
/// <param name="sprite"></param>
/// <returns></returns>
public static Texture2D TextureToSprite(Sprite sprite)
{
// 获取 Sprite 的纹理
Texture2D texture = sprite.texture;
// 创建一个新的 Texture2D 用于存储 Sprite 的图像数据
Texture2D texture2D = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height);
// 读取 Sprite 的像素数据到新的 Texture2D
Color[] pixels = texture.GetPixels(
(int)sprite.rect.x,
(int)sprite.rect.y,
(int)sprite.rect.width,
(int)sprite.rect.height
);
// 将像素数据设置到新的 Texture2D 中
texture2D.SetPixels(pixels);
texture2D.Apply(); // 应用更改
return texture2D;
}
/// <summary>
/// 纹理转精灵图片
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
public static Sprite TextureToSprite(Texture2D texture)
{
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
new Vector2(0.5f, 0.5f));
return sprite;
}
/// <summary>
/// 截取相机画面内容并返回()
/// </summary>
/// <param name="camera"></param>
/// <returns></returns>
public static Texture2D SaveCameraToTexture(Camera camera)
{
Texture2D capturedImage;
var renderTexture = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 24);
camera.targetTexture = renderTexture;
// 创建一个 Texture2D 用来存储相机捕捉的画面
capturedImage = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);
// 从 RenderTexture 中读取像素数据到 Texture2D
RenderTexture.active = renderTexture;
capturedImage.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
capturedImage.Apply();
// 重置 RenderTexture 的激活状态
RenderTexture.active = null;
// 此时 capturedImage 就包含了当前帧的画面,你可以进行保存或者其他操作
return capturedImage;
}
}
}