美文网首页
Unity3d通用工具类之NGUI图集分解

Unity3d通用工具类之NGUI图集分解

作者: 与诗共远方 | 来源:发表于2017-09-25 19:45 被阅读0次

原文地址:http://www.cnblogs.com/CaomaoUnity3d/p/6043395.html

原文补充:Directory在System.IO 空间下,所以需要导入这个System.IO

Unity3d通用工具类之NGUI图集分解

由于最近需要一些美术资源吗,但是无奈自己不会制作UI,所以就打算去网上的项目中直接找几张可以使用的贴图资源。

但是发现这些资源已经被NGUI自带的打包图集工具打包好了,而且原小贴图也已经全部删掉了,只剩下一个预制物。

那么这个预制物里面包含什么呢:

1.一张大图集贴图

2.大贴图的材质球

3.挂上UIAtla脚本的预制物

那么重点来了,我们该如何获取这张大贴图中的小贴图呢?

这里我写了个小插件,我直接在NGUI源代码里面改:

找到NGUI的源代码:UIAtlasMaker

在OnGUI方法里面,我新添加了可以导出贴图的代码:

GUILayout.BeginHorizontal();

{

if(tex !=null)

{

if(GUILayout.Button("导出贴图(PNG)",GUILayout.Width(120f)))

{

stringfilePath = EditorUtility.SaveFolderPanel("保存贴图到指定文件夹","","");

ExportTexturePNGFromAtlas(filePath, NGUISettings.atlas);

}

}

}

GUILayout.EndHorizontal();

ExportTexturePNGFromAtlas():

staticvoidExportTexturePNGFromAtlas(stringfolderPath,UIAtlas atlas)

{

List exitSpritesList = atlas.spriteList;

Texture2D atlasTexture = NGUIEditorTools.ImportTexture(atlas.texture,true,false, !atlas.premultipliedAlpha);

intoldwith = atlasTexture.width;

intoldHeight = atlasTexture.height;

Color32[] oldPixels =null;

foreach(varesinexitSpritesList)

{

intxmin = Mathf.Clamp(es.x, 0, oldwith);

intymin = Mathf.Clamp(es.y, 0, oldHeight);

intnewWidth = Mathf.Clamp(es.width, 0, oldwith);

intnewHeight = Mathf.Clamp(es.height, 0, oldHeight);

if(newWidth == 0 || newHeight == 0)continue;

if(oldPixels ==null) oldPixels = atlasTexture.GetPixels32();

Color32[] newPixels =newColor32[newWidth * newHeight];

for(inty = 0; y < newHeight; ++y)

{

for(intx = 0; x < newWidth; ++x)

{

intnewIndex = (newHeight - 1 - y) * newWidth + x;

intoldIndex = (oldHeight - 1 - (ymin + y)) * oldwith + (xmin + x);

newPixels[newIndex] = oldPixels[oldIndex];

}

}

Texture2D t =newTexture2D(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 =newFileStream(folderPath +"/"+ es.name +".png", FileMode.CreateNew))

{

BinaryWriter writer =newBinaryWriter(fs);

writer.Write(bytes);

}

}

}

打开NGUI的Atlas Maker:

点击导出贴图,然后会弹出选择保存贴图到哪个文件夹,点击选择文件夹之后,小贴图就导出成功了。

相关文章

网友评论

      本文标题:Unity3d通用工具类之NGUI图集分解

      本文链接:https://www.haomeiwen.com/subject/laidextx.html