Unity2D图集的剪裁
转载http://blog.****.net/hongyouwei/article/details/45011315
- Unity3D拓展菜单
[MenuItem("Assets/Tools/剪切2d sprite小工具")]
- 获取当前点击的对象,与需要剪裁的图片路径(自定义)
- AssetDatabase.GetAssetPath(image);//获取image文件在assets下的路径(包含文件名)
- Path.GetDirectoryName(path)//获取path路径的目录名(不包含文件名)
Texture2D image = Selection.activeObject as Texture2D;//获取当前选择的对象
string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image));//获取image路径名称
string path = rootPath + "/" + image.name + ".PNG";//图片路径名称
- 获取图片入口
TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;//获取图片入口
- 创建文件夹
AssetDatabase.CreateFolder(rootPath, image.name)//在path下创建文件夹名
- 遍历图集
foreach (SpriteMetaData metaData in texImp.spritesheet)//遍历小图集
{
Texture2D myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);
//abc_0:(x:2.00, y:400.00, width:103.00, height:112.00)
//小图的rect.x,rect.y 位置开始相当于图的(0,0)开始到图的(width,height)位置每像素循环
for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++)//Y轴像素
{
for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)
//image像素位置赋值到myimage处
myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));
}
//转换纹理到EncodeToPNG兼容格式
if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24)
{
Texture2D newTexture = new Texture2D(myimage.width, myimage.height);
newTexture.SetPixels(myimage.GetPixels(0), 0);
myimage = newTexture;
}
var pngData = myimage.EncodeToPNG();
//AssetDatabase.CreateAsset(myimage, rootPath + "/" + image.name + "/" + metaData.name + ".PNG");
File.WriteAllBytes(rootPath + "/" + image.name + "/" + metaData.name + ".PNG", pngData);
// 刷新资源窗口界面
AssetDatabase.Refresh();
}