64 lines
2.3 KiB
C#
64 lines
2.3 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
using Object = UnityEngine.Object;
|
|
|
|
public class SplitTextureUtil
|
|
{
|
|
[MenuItem("Assets/切图")]
|
|
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);
|
|
}
|
|
}
|
|
|
|
public static void SplitTexture(Texture2D texture, int width, int height, string directory)
|
|
{
|
|
var row = texture.height / height + 1;
|
|
var column = texture.width / width + 1;
|
|
var rowReminder = texture.height % height;
|
|
var columnReminder = texture.width % width;
|
|
|
|
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 = new Texture2D(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.EncodeToJPG();
|
|
var path = $"{directory}/{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();
|
|
}
|
|
}
|
|
}
|
|
} |