Unity开发中经常会用到将多个图片显示在一个Image组件上
比如:关卡预览、头像选择等
实现原理:
- 创建一个新的Texture2D
- 将待合成的Texture2D分别置于新的Texture2D的不用位置
- 转换为Sprite进行展示
代码
-
TextureKit
- 负责对 Texture2D 的合成,可指定行数、列数
public static class TextureKit
{
public static Texture2D CombineTextures(Texture2D[] textures, int row, int column)
{
int width = textures[0].width;
int height = textures[0].height;
// 创建一个新的纹理,宽度为3个纹理的宽度,高度为2个纹理的高度
Texture2D combinedTexture = new Texture2D(width * column, height * row, TextureFormat.RGBA32, false);
// 遍历每个纹理并设置它们的像素
for (int i = 0; i < textures.Length; i++)
{
int xOffset = (i % column) * width; // 每排纹理
int yOffset = (1 - i / column) * height; // 上排从1-0, 下排从0-1
// 如果是默认纹理(如黑色或白色纹理),则填充透明像素
if (textures[i] == Texture2D.blackTexture || textures[i] == Texture2D.whiteTexture)
{
Color[] clearPixels = new Color[width * height];
for (int j = 0; j < clearPixels.Length; j++)
clearPixels[j] = Color.clear;
combinedTexture.SetPixels(xOffset, yOffset, width, height, clearPixels);
}
else
{
Color[] pixels = textures[i].GetPixels();
combinedTexture.SetPixels(xOffset, yOffset, width, height, pixels);
}
}
// 应用更改
combinedTexture.Apply();
return combinedTexture;
}
}
- ImageKit
- Image组件扩展,将Texture2D转换为Sprite赋值为Image组件
public static class ImageKit
{
public static void CombineTextures(this Image image, Texture2D[] textures, int row, int column)
{
var combineTextures = TextureKit.CombineTextures(textures, row, column);
var sprite = Sprite.Create(combineTextures, new Rect(0, 0, combineTextures.width, combineTextures.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
}
}
- Test
- 测试脚本
public class Test : MonoBehaviour
{
public Image image;
void Start()
{
var loadAll = Resources.LoadAll<Texture2D>("");
List<Texture2D> list = new List<Texture2D>();
for (int i = 0; i < 6; i++)
{
list.Add(loadAll[i]);
}
image.CombineTextures(list.ToArray(),2,3);
}
}