Unity3d通用工具类之NGUI图集分解
---恢复内容开始---
Unity3d通用工具类之NGUI图集分解
由于最近需要一些美术资源吗,但是无奈自己不会制作UI,所以就打算去网上的项目中直接找几张可以使用的贴图资源。
但是发现这些资源已经被NGUI自带的打包图集工具打包好了,而且原小贴图也已经全部删掉了,只剩下一个预制物。
那么这个预制物里面包含什么呢:
1.一张大图集贴图
2.大贴图的材质球
3.挂上UIAtla脚本的预制物
那么重点来了,我们该如何获取这张大贴图中的小贴图呢?
这里我写了个小插件,我直接在NGUI源代码里面改:
找到NGUI的源代码:UIAtlasMaker
在OnGUI方法里面,我新添加了可以导出贴图的代码:
1
2
3
4
5
6
7
8
9
10
11
12
|
GUILayout.BeginHorizontal(); { if (tex != null )
{
if (GUILayout.Button( "导出贴图(PNG)" ,GUILayout.Width(120f)))
{
string filePath = EditorUtility.SaveFolderPanel( "保存贴图到指定文件夹" , "" , "" );
ExportTexturePNGFromAtlas(filePath, NGUISettings.atlas);
}
}
} GUILayout.EndHorizontal(); |
ExportTexturePNGFromAtlas():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
static void ExportTexturePNGFromAtlas( string folderPath,UIAtlas atlas)
{ List<UISpriteData> exitSpritesList = atlas.spriteList;
Texture2D atlasTexture = NGUIEditorTools.ImportTexture(atlas.texture, true , false , !atlas.premultipliedAlpha);
int oldwith = atlasTexture.width;
int oldHeight = atlasTexture.height;
Color32[] oldPixels = null ;
foreach ( var es in exitSpritesList)
{
int xmin = Mathf.Clamp(es.x, 0, oldwith);
int ymin = Mathf.Clamp(es.y, 0, oldHeight);
int newWidth = Mathf.Clamp(es.width, 0, oldwith);
int newHeight = Mathf.Clamp(es.height, 0, oldHeight);
if (newWidth == 0 || newHeight == 0) continue ;
if (oldPixels == null ) oldPixels = atlasTexture.GetPixels32();
Color32[] newPixels = new Color32[newWidth * newHeight];
for ( int y = 0; y < newHeight; ++y)
{
for ( int x = 0; x < newWidth; ++x)
{
int newIndex = (newHeight - 1 - y) * newWidth + x;
int oldIndex = (oldHeight - 1 - (ymin + y)) * oldwith + (xmin + x);
newPixels[newIndex] = oldPixels[oldIndex];
}
}
Texture2D t = new Texture2D(newWidth, newHeight);
t.SetPixels32(newPixels);
t.Apply();
byte [] bytes = t.EncodeToPNG();
Texture2D.DestroyImmediate(t);
t = null ;
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream fs = new FileStream(folderPath + "/" + es.name + ".png" , FileMode.CreateNew))
{
BinaryWriter writer = new BinaryWriter(fs);
writer.Write(bytes);
}
}
} |
打开NGUI的Atlas Maker:
点击导出贴图,然后会弹出选择保存贴图到哪个文件夹,点击选择文件夹之后,小贴图就导出成功了。
转载学习