Unity實現切割圖集工具

本文實例為大傢分享瞭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();
        }
    }
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: