原文地址:http://www.cnblogs.com/CaomaoUnity3d/p/6043395.html
原文補(bǔ)充:Directory在System.IO 空間下,所以需要導(dǎo)入這個(gè)System.IO
Unity3d通用工具類之NGUI圖集分解
由于最近需要一些美術(shù)資源嗎民鼓,但是無(wú)奈自己不會(huì)制作UI癞蚕,所以就打算去網(wǎng)上的項(xiàng)目中直接找?guī)讖埧梢允褂玫馁N圖資源计螺。
但是發(fā)現(xiàn)這些資源已經(jīng)被NGUI自帶的打包圖集工具打包好了,而且原小貼圖也已經(jīng)全部刪掉了乒躺,只剩下一個(gè)預(yù)制物。
那么這個(gè)預(yù)制物里面包含什么呢:
1.一張大圖集貼圖
2.大貼圖的材質(zhì)球
3.掛上UIAtla腳本的預(yù)制物
那么重點(diǎn)來(lái)了,我們?cè)撊绾潍@取這張大貼圖中的小貼圖呢争涌?
這里我寫了個(gè)小插件,我直接在NGUI源代碼里面改:
找到NGUI的源代碼:UIAtlasMaker
在OnGUI方法里面辣恋,我新添加了可以導(dǎo)出貼圖的代碼:
GUILayout.BeginHorizontal();
{
if(tex !=null)
{
if(GUILayout.Button("導(dǎo)出貼圖(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:
點(diǎn)擊導(dǎo)出貼圖亮垫,然后會(huì)彈出選擇保存貼圖到哪個(gè)文件夾,點(diǎn)擊選擇文件夾之后伟骨,小貼圖就導(dǎo)出成功了饮潦。