码迷,mamicode.com
首页 > 编程语言 > 详细

Unity 图片分割将spirte保存在本地

时间:2015-01-15 23:35:33      阅读:458      评论:0      收藏:0      [点我收藏+]

标签:

如果你拿到的是一张整图,你想分割之后使用NGUI sprite来使用!  下面就能解决的需求.

技术分享

步骤:

1. 使用Unity自带的spirte进行分割图片

2. 使用代码把分割出来的2DSpirte转换成本地PNG图片,再导入Unity使用atlas纹理O(∩_∩)O~

注意事项:

1.  图片切换成Advanced类型 Read/Write Enabled勾上,不然会抛出异常

 

直接上代码:

[MenuItem("Tools/导出精灵")]
    static void SaveSprite() 
    {
        //每一张贴图类型Advanced下 Read/Write Enabled打上勾才能进行文件读取
        string resourcesPath = @"Assets/Resources/";
        foreach (Object obj in Selection.objects)
        {

            string selectionPath = AssetDatabase.GetAssetPath(obj);

            // 必须最上级是"Assets/Resources/"
            if (selectionPath.StartsWith(resourcesPath))
            {
                //获取文件后罪名.png
                string selectionExt = System.IO.Path.GetExtension(selectionPath);
                
                if (selectionExt.Length == 0) continue;

                // 从路径"Assets/Resources/UI/testUI.png"得到路径"UI/testUI"
                string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
                loadPath = loadPath.Substring(resourcesPath.Length);

                //加载此文件下的所有资源
                Sprite [] spriteList = Resources.LoadAll<Sprite>(loadPath);

                if(spriteList.Length > 0)
                {
                    //创建导出文件夹
                    string outPath = Application.dataPath + "/outSprite/" + loadPath;
                    System.IO.Directory.CreateDirectory(outPath);
                    
                    foreach (var sprite in spriteList)
                    {
                        Texture2D tex = new Texture2D((int)sprite.rect.width,(int)sprite.rect.height,sprite.texture.format,false);
                        tex.SetPixels(sprite.texture.GetPixels((int)sprite.rect.xMin
                                                    ,(int)sprite.rect.yMin
                                                    ,(int)sprite.rect.width
                                                    ,(int)sprite.rect.height));
                        tex.Apply();

                        //写出成png文件
                        System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png",tex.EncodeToPNG());
                        Debug.Log("SaveSprite to" + outPath);   
                    }
                    Debug.Log("保存图片完毕!" + outPath);
                }
            }
        }
    }

Unity 图片分割将spirte保存在本地

标签:

原文地址:http://www.cnblogs.com/plateFace/p/4227373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!