其他分享
首页 > 其他分享> > Unity2D图集剪裁

Unity2D图集剪裁

作者:互联网

Unity2D图集的剪裁

转载http://blog.csdn.net/hongyouwei/article/details/45011315

  [MenuItem("Assets/Tools/剪切2d sprite小工具")]
        Texture2D image = Selection.activeObject as Texture2D;//获取当前选择的对象
        string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image));//获取image路径名称
        string path = rootPath + "/" + image.name + ".PNG";//图片路径名称
TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;//获取图片入口
AssetDatabase.CreateFolder(rootPath, image.name)//在path下创建文件夹名
        foreach (SpriteMetaData metaData in texImp.spritesheet)//遍历小图集
        {
        
            Texture2D myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);
            //abc_0:(x:2.00, y:400.00, width:103.00, height:112.00)
            //小图的rect.x,rect.y 位置开始相当于图的(0,0)开始到图的(width,height)位置每像素循环
            for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++)//Y轴像素
            {
                for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)
                //image像素位置赋值到myimage处
                    myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));
            }
            //转换纹理到EncodeToPNG兼容格式
            if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24)
            {
                Texture2D newTexture = new Texture2D(myimage.width, myimage.height);               
                newTexture.SetPixels(myimage.GetPixels(0), 0);
                myimage = newTexture;
            }
            var pngData = myimage.EncodeToPNG();
            //AssetDatabase.CreateAsset(myimage, rootPath + "/" + image.name + "/" + metaData.name + ".PNG");
            File.WriteAllBytes(rootPath + "/" + image.name + "/" + metaData.name + ".PNG", pngData);
            // 刷新资源窗口界面
            AssetDatabase.Refresh();
        }

标签:Unity2D,int,image,myimage,图集,Texture2D,剪裁,rect,metaData
来源: https://blog.csdn.net/m0_43408361/article/details/90083470