利用Unity自带的合图切割功能将合图切割成子图

转载的,牛人无处不在,我还太渺小

虽然目前网上具有切割合图功能的工具不少,但大部分都是自动切割或者根据plist之类的合图文件切割的,

这种切割往往不可自己微调或者很难维调,导致效果不理想。

今天逛贴吧发现了一位网友写的切割合图插件很不错,就分享下,

利用的是Unity自带的合图切割功能,原生的切割功能虽然很方便而且很容易微调,但无法导出,这个网友将它们导出了,

来自:百度Unity3D贴吧的13471713164

链接:http://tieba.baidu.com/p/3217039693

 1 using UnityEngine;
 2 using UnityEditor;
 3 using System.Collections.Generic;
 4 using System.IO;
 5 
 6 /// <summary>
 7 /// 可以将Unity里自带的合图切割功能切割后的合图导出为子图
 8 /// 使用方法:
 9 /// 1.先导入Png合图
10 /// 2.图片Texture Type要选择Advanced并且下面那个Read/Wite Enable要打勾
11 /// 3.将图片格式设置为合图“mult”,并点击“Editor”开始切割合图
12 /// 4.切割完毕后先选中该张图片,点击Process to Sprites后便可以导出
13 /// </summary>
14 public static class SpriteSheetPackerImport
15 {
16     [MenuItem("Assets/Sprite Sheet Packer/Process to Sprites")]
17     static void ProcessToSprite()
18     {
19         Texture2D image = Selection.activeObject as Texture2D;                          //获取旋转的对象
20         string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image));     //获取路径名称
21         string path = rootPath + "/" + image.name + ".PNG";                             //图片路径名称
22 
23 
24         TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;
25 
26 
27         AssetDatabase.CreateFolder(rootPath, image.name);                               //创建文件夹
28 
29 
30         foreach (SpriteMetaData metaData in texImp.spritesheet)                         //遍历小图集
31         {
32             Texture2D myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);
33 
34 
35             //abc_0:(x:2.00, y:400.00, 103.00, height:112.00)
36             for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++)//Y轴像素
37             {
38                 for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)
39                     myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));
40             }
41 
42 
43             //转换纹理到EncodeToPNG兼容格式
44             if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24)
45             {
46                 Texture2D newTexture = new Texture2D(myimage.width, myimage.height);
47                 newTexture.SetPixels(myimage.GetPixels(0), 0);
48                 myimage = newTexture;
49             }
50             var pngData = myimage.EncodeToPNG();
51 
52 
53             //AssetDatabase.CreateAsset(myimage, rootPath + "/" + image.name + "/" + metaData.name + ".PNG");
54             File.WriteAllBytes(rootPath + "/" + image.name + "/" + metaData.name + ".PNG", pngData);
55         }
56     }
57 }

本代码添加在 Asset/Editor 目录下 才会生效,

依据上述步骤,

在想要才分的图集的图片 右键  -> Sprite Sheet Packer -> Process to Sprite

之后就会在同目录下生成一个相同图集文件名的文件夹,里面就是才分出来的图集的每个资源了

原文地址:https://www.cnblogs.com/dudu580231/p/7263720.html