2024-12-17 23:11:00 +08:00
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
|
|
namespace ZXL.Helper
|
|
|
|
|
{
|
|
|
|
|
public static class TextureHelper
|
|
|
|
|
{
|
2024-12-18 11:32:47 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// 精灵图片转纹理
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="sprite"></param>
|
|
|
|
|
/// <returns></returns>
|
2024-12-17 23:11:00 +08:00
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-18 11:32:47 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// 纹理转精灵图片
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="texture"></param>
|
|
|
|
|
/// <returns></returns>
|
2024-12-17 23:11:00 +08:00
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-18 11:32:47 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// 截取相机画面内容并返回()
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="camera"></param>
|
|
|
|
|
/// <returns></returns>
|
2024-12-17 23:11:00 +08:00
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|