TexturePacker 图集生成工具

TexturePacker 可以通过命令行方式,批量生成图集,TexturePacker相关命令可以参考 https://blog.csdn.net/u014065445/article/details/54289787

unity中使用的方式是,通过C#中的Process类,创建一个独立进程,执行命令行脚本,完成图集生成和切分

Mac平台的shell脚本


./TexturePacker \
--sheet $3/$1_{n}.png \
--data $3/$1_{n}.txt $2 \
--format unity \
--trim-sprite-names \
--basic-sort-by Name \
--basic-order Descending \
--max-size $4 \
--size-constraints POT \
--force-squared \
--border-padding 1 \
--shape-padding 2 \
--disable-rotation \
--trim-mode None \
--disable-auto-alias \
--multipack

Windows平台的bat脚本

@echo off
start TexturePacker.exe %2 --sheet %3/%1_{n}.png --data %3/%1_{n}.txt %2 ^
--format unity --trim-sprite-names --basic-sort-by Name --basic-order Descending ^
--max-size %4 --size-constraints POT --force-squared --border-padding 1 --shape-padding 2 ^
--disable-rotation --trim-mode None --disable-auto-alias --multipack --extrude 0

unity编辑器脚本


using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Diagnostics;
using System;
using System.Text;
using LitJson;
​
public class BuildAtlasToolEditor  {
​
  public static string spriteFolder = "Assets/AssetBundleData/Image";
  public static string atlasFolder = "Assets/AssetBundleData/UI/Atlas";
​
​
  [MenuItem("Assets/Build Atlas/Build For Folder")]
  static void BuildForSelectedFolder()
  {
    string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
    BuildForFolder(assetPath);
  }
  [MenuItem("Assets/Build Atlas/Build For Folder", true)]
  static bool ValidateBuildForSelectedFolder()
  {
    string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
    string[] tempList = assetPath.Split('/');
    if(assetPath.Contains(spriteFolder) &&
       tempList.Length > 1)
    {
      return true;
    }
    return false;
  }
  private static void BuildForFolder(string assetPath)
  {
    //将路径切割
    string[] tempList = assetPath.Split('/');
    string atlasName = tempList[tempList.Length - 1];
    string spritePath = Path.Combine(Application.dataPath, assetPath.Replace("Assets/", ""));
    string atlasPath = Path.Combine(Application.dataPath, atlasFolder.Replace("Assets/", ""));
    int size = 1024;
    
    Process process = new Process();
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
​
#if UNITY_EDITOR_OSX
    psi.FileName = "/bin/sh";
        psi.WorkingDirectory = Path.Combine(Application.dataPath, "../../Tools/TexturePacker/mac/TexturePacker.app/Contents/MacOS");
    psi.Arguments = Path.Combine(Application.dataPath, "Editor/SpriteEditor/PackTexture.sh")
              + " " + atlasName
            + " " + spritePath
            + " " + atlasPath
            + " " + size;
#elif UNITY_STANDALONE_WIN
        psi.FileName = "PackTexture.bat";
        psi.WorkingDirectory = Path.Combine(Application.dataPath, "../../Tools/TexturePacker/wins/bin");
        psi.Arguments = Path.Combine(Application.dataPath, "Editor/SpriteEditor/PackTexture.bat")
                  + " " + atlasName
                  + " " + spritePath
                  + " " + atlasPath
                  + " " + size;
#endif
        process.StartInfo = psi;
        try
    {
            if (process.Start())
      {
        string strOutput = process.StandardOutput.ReadToEnd();
                string errorInfo = process.StandardError.ReadToEnd();
        process.WaitForExit();
        process.Close();
                if (!string.IsNullOrEmpty(strOutput)) {
                    Debug.Log("Console outPut: " + strOutput);
                }
                if (!string.IsNullOrEmpty(errorInfo))
                {
                    Debug.LogError("Console errorInfo: " + errorInfo);
                }
            }
    }
    catch (Exception e)
    {
      process.Close();
      UnityEngine.Debug.LogError("========Fail to batch " + atlasName + ":" +e.ToString());
      return;
    }
    AssetDatabase.Refresh();
        SplitAtlasSprites(atlasName);
  }
​
    static void SplitAtlasSprites(string atlasName)
    {
        for (int i = 0; ; i++)
        {
            string texturePath = Path.Combine(atlasFolder, atlasName + "_" + i + ".png");
            string textureFullPath = Path.Combine(Application.dataPath, texturePath.Replace("Assets/", ""));
            if (!File.Exists(textureFullPath))
            {
                break;
            }
            TextureImporter ti = AssetImporter.GetAtPath(texturePath) as TextureImporter;
            ti.textureType = TextureImporterType.Sprite;
            ti.spriteImportMode = SpriteImportMode.Multiple;
            ti.mipmapEnabled = false;
​
            TextureImporterSettings tis = new TextureImporterSettings();
            ti.ReadTextureSettings(tis);
            tis.spriteMeshType = SpriteMeshType.Tight;
            tis.spriteExtrude = 0;
            //tis.alphaSource = TextureImporterAlphaSource.None;  
            ti.SetTextureSettings(tis);
​
            string jsonPath = Path.Combine(atlasFolder, atlasName + "_" + i + ".txt");
            string jsonFullPath = Path.Combine(Application.dataPath, jsonPath.Replace("Assets/", ""));
            string configJson = File.ReadAllText(jsonFullPath, Encoding.UTF8);
            JsonData configJsonData = JsonMapper.ToObject(configJson);
            int textureHeight = int.Parse(configJsonData["meta"]["size"]["h"].ToString());
            JsonData tempJsonData = configJsonData["frames"];
            List<SpriteMetaData> metas = new List<SpriteMetaData>();
            foreach (string name in tempJsonData.Keys)
            {
                JsonData frameData = tempJsonData[name]["frame"];
                int x = int.Parse(frameData["x"].ToString());
                int y = int.Parse(frameData["y"].ToString());
                int w = int.Parse(frameData["w"].ToString());
                int h = int.Parse(frameData["h"].ToString());
                SpriteMetaData meta = new SpriteMetaData();
                string subSpritePath = string.Format("Assets/AssetBundleData/UI/{0}/{1}.png", atlasName, name);
                Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(subSpritePath);
                if (sprite != null && sprite.border != null)
                {
                    UnityEngine.Debug.Log(sprite.border);
                    // meta.border = new Vector4(sprite.border.x, sprite.border.y, sprite.border.w, sprite.border.z);
                    meta.border = sprite.border;
                }
                meta.pivot = new Vector2(0.5f, 0.5f);
                meta.alignment = (int)SpriteAlignment.Center;
                meta.rect = new Rect(x, textureHeight - y - h, w, h);
                meta.name = name;
                metas.Add(meta);
            }
            ti.spritesheet = metas.ToArray();
            ti.SaveAndReimport();
            AssetDatabase.DeleteAsset(jsonPath);
            //AssetDatabase.Refresh();
        }
        //AssetDatabase.Refresh();
    }
}


为了防止误操作,这里对可打图集的资源目录做了限制

	[MenuItem("Assets/Build Atlas/Build For Folder", true)]
	static bool ValidateBuildForSelectedFolder()
	{
		string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
		string[] tempList = assetPath.Split('/');
		if(assetPath.Contains(spriteFolder) &&
		   tempList.Length > 1)
		{
			return true;
		}
		return false;
	}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: TexturePacker是一个强大的工具,用于制作和编辑图像的精灵表或图集,这使得游戏开发者可以有效地管理和提高游戏的性能。TexturePacker还提供了一种方便的方法,通过拆分图集,将大型图像资源分解为更小的部件,以便在游戏中更好地使用。 拆分图集可以通过多种方式实现,其中一个流行的方法是使用TexturePacker的命令行选项。通过使用命令行选项,可以自动化拆分图集的过程,并根据需要生成多个子图像资源。这对于大型游戏项目特别有用,因为游戏需要处理大量的图像资源,而拆分图集可以大大减少应用程序的加载和处理时间。 使用TexturePacker进行图集拆分时,可以选择多种拆分选项。例如,可以将图像资源按行或列分割,在固定的边框或网格上分割,或使用自定义切割边框。这意味着开发者可以完全控制拆分过程,以确保生成最优化的子图像资源。 总之,TexturePacker图集拆分功能提供了一种完全可定制的方法,以在游戏中轻松管理和加载大量图像资源。它不仅可以提高游戏的性能和加载速度,还可以减轻开发者的负担,使其更专注于游戏的核心功能。 ### 回答2: TexturePacker是一款常用的纹理打包工具,可以将多个小图合并成一张图集进行优化,提高游戏或应用的性能和加载速度。而拆分图集则是将一个大的图集按照指定的规则进行切分,分离出多张小的图集。 使用TexturePacker拆分图集可以使得游戏或应用更加灵活,可以根据场景需要加载不同的图集,减少资源浪费。同时也可以方便地进行图集的维护和优化,提高整个项目的可维护性和效率。 拆分图集的方法有多种,可以按照文件名、大小、引用次数等规则进行切分。在TexturePacker工具中,可以通过选择“多文件输出”来实现拆分图集功能,选择合适的规则进行配置即可。在导出图集时,生成多张小的图集,每张图集包含指定的纹理,可以根据需要分别加载。 需要注意的是,拆分图集虽然提高了灵活性和可维护性,但也会增加文件数量和加载次数,可能会影响到游戏或应用的性能。因此在使用时需要根据实际情况进行权衡和优化。 ### 回答3: TexturePacker是一个非常方便的工具,它可以将多张图片合并成一个大的图集,以提高游戏或应用程序的性能和加载速度。但是,当图集非常大时,可能会导致内存占用过高或加载速度变慢。在这种情况下,可以使用TexturePacker的拆分功能,将大图集拆分成多个小图集。 拆分图集的步骤非常简单。首先打开TexturePacker,选择要拆分的图集并点击“Split”按钮。然后,选择一个合适的输出目录和文件名前缀,并定义拆分的数量和方式。可以按像素大小或图像数量拆分,并设置间隙和边距。最后,单击“Publish”按钮,TexturePacker会根据你的设置自动拆分图集生成多个小图集。 拆分后,你的代码需要进行相应的更改,以便正确加载拆分后的图集。在访问图集时,你应该使用一个列表或数组,并遍历所有拆分的图集,并将它们合并成一个最终的纹理。这可以通过loadTextures方法或类似方法实现,其中,你需要指定分别加载每个小图集的路径和文件名,并将它们组合成一个单个的纹理开发包。 总之,使用TexturePacker拆分图集是提高游戏或应用程序性能和加载速度的好方法。虽然拆分后的图集需要一些额外的代码来加载和管理,但这可以保证你的应用程序在运行时更有效率并降低内存占用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯过客TYGK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值