Unity实现切割图集工具

2022-07-23,,,

本文实例为大家分享了unity实现切割图集工具的具体代码,供大家参考,具体内容如下

操作步骤

先将脚本拖入editor

1.选中要切割的图片,texture type 选为default,并勾选advanced下的read/write enabled

2.texture type改为sprite(2d and ui),sprite mode 选为multiple,apply一下

3.sprite editor 先选其他的切一下,在选第一个切一下,切割成小图,apply

4.选中图集右键,imageslicer,process to sprites

5.等待切割完成后就可以在同级目录的同名文件夹下使用了

使用时要把小图type改为sprite(2d and ui),也可以更改名字

脚本如下

using unityengine;
using system.collections;
using unityeditor;
using system.io;
using system.collections.generic;
/// <summary>
/// 切割
/// </summary>
public static class imageslicer
{
    [menuitem("assets/imageslicer/process to sprites")]
    static void processtosprite()
    {
        texture2d image = selection.activeobject as texture2d;//获取旋转的对象
        string rootpath = path.getdirectoryname(assetdatabase.getassetpath(image));//获取路径名称
        string path = rootpath + "/" + image.name + ".png";//图片路径名称


        textureimporter teximp = assetimporter.getatpath(path) as textureimporter;//获取图片入口


        assetdatabase.createfolder(rootpath, image.name);//创建文件夹


        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)
            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++)
                    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();
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《Unity实现切割图集工具.doc》

下载本文的Word格式文档,以方便收藏与打印。