89 lines
3.4 KiB
C#
89 lines
3.4 KiB
C#
using System;
|
|
using System.IO;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
using Object = UnityEngine.Object;
|
|
|
|
public class SplitTextureUtil
|
|
{
|
|
[MenuItem("Assets/*Custom/贴图/切图")]
|
|
public static void SplitTexture()
|
|
{
|
|
var texture = Selection.activeObject as Texture2D;
|
|
if (texture)
|
|
{
|
|
var path = AssetDatabase.GetAssetPath(texture);
|
|
var dir = Path.GetDirectoryName(path).Replace("\\", "/");
|
|
SplitTexture(texture, 1024, 1024, dir, "");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 分割贴图
|
|
/// </summary>
|
|
/// <param name="texture">要分割的贴图</param>
|
|
/// <param name="width">分割后的块的宽度(像素)</param>
|
|
/// <param name="height">分割后的块的高度(像素)</param>
|
|
/// <param name="directory">分割后贴图的位置</param>
|
|
/// <param name="prefix">文件名前缀(可选)</param>
|
|
public static Texture2D[,] SplitTexture(Texture2D texture, int width, int height, string directory, string prefix = "")
|
|
{
|
|
var row = Mathf.CeilToInt(texture.height * 1f / height);
|
|
var column = Mathf.CeilToInt(texture.width * 1f / width);
|
|
var rowReminder = texture.height % height;
|
|
if (rowReminder == 0)
|
|
rowReminder = height;
|
|
var columnReminder = texture.width % width;
|
|
if (columnReminder == 0)
|
|
columnReminder = width;
|
|
|
|
Texture2D[,] result = new Texture2D[row, column];
|
|
|
|
var allPixels = texture.GetPixels();
|
|
for (int r = 0; r < row; r++)
|
|
{
|
|
for (int c = 0; c < column; c++)
|
|
{
|
|
var realWidth = c == column - 1 ? columnReminder : width;
|
|
var realHeight = r == row - 1 ? rowReminder : height;
|
|
|
|
var pixelCount = realWidth * realHeight;
|
|
var textureOutput = PhxhSDK.Utils.CreateTexture($"split_{texture.name}_{r}_{c}", realWidth, realHeight);
|
|
Color[] pixels = new Color[pixelCount];
|
|
var startIndex = r * height * texture.width + c * width;
|
|
for (int i = 0; i < pixelCount; i++)
|
|
{
|
|
var innerRow = i / realWidth;
|
|
var innerColumn = i % realWidth;
|
|
var pickIndex = startIndex + innerRow * texture.width + innerColumn;
|
|
pixels[i] = allPixels[pickIndex];
|
|
}
|
|
|
|
textureOutput.SetPixels(pixels);
|
|
Byte[] bytes = textureOutput.EncodeToPNG();
|
|
var path = $"{directory}/{prefix}split_{texture.name}_{r}_{c}.jpg";
|
|
FileStream fs = File.Open(path, FileMode.Create);
|
|
BinaryWriter writer = new BinaryWriter(fs);
|
|
writer.Write(bytes);
|
|
writer.Flush();
|
|
writer.Close();
|
|
fs.Close();
|
|
Object.DestroyImmediate(textureOutput);
|
|
AssetDatabase.Refresh();
|
|
|
|
// 获取图片设置
|
|
var importer = AssetImporter.GetAtPath(path) as TextureImporter;
|
|
if (importer != null)
|
|
{
|
|
importer.alphaIsTransparency = true;
|
|
importer.SaveAndReimport();
|
|
}
|
|
AssetDatabase.Refresh();
|
|
|
|
result[r, c] = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
} |