導入圖片時設置默認格式


當我們將圖片導入到工程中時,unity 3d會對圖片進行處理,設置圖片的默認格式。如下圖所示,是圖片導入到工程中,unity 3d進行的默認設置。

但是,一般情況下,這樣的圖片格式並不能滿足我們的需求。所以我就想,有沒有辦法修改圖片導入時設置的格式呢?答案是有的。
首先說一下思路:
1. 我們可以在Assets文件夾下建立一個文件夾,例如:GameResources。只有當將圖片導入GameResources文件夾內時,才會對圖片進行處理。
2. 有些圖片需要打包到圖集中。那么,我們可以在GameResources下面建立以圖集名命名的文件夾,例如:UI。UI文件夾下的圖片的圖集都會被設置為UI。
3. 有時我們的工程中不希望導入某些類型的圖片,例如.dds。那么可以對該類型的圖片進行過濾。
代碼如下:

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Reflection;

public class ImportSetting : AssetPostprocessor
{
    static int[] maxSizes = { 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
    static readonly string DEFAULTS_KEY = "DEFAULTS_DONE";
    static readonly uint DEFAULTS_VERSION = 2;

    public bool IsAssetProcessed
    {
        get
        {
            string key = string.Format("{0}_{1}", DEFAULTS_KEY, DEFAULTS_VERSION);
            return assetImporter.userData.Contains(key);
        }
        set
        {
            string key = string.Format("{0}_{1}", DEFAULTS_KEY, DEFAULTS_VERSION);
            assetImporter.userData = value ? key : string.Empty;
        }
    }

    void OnPreprocessTexture()
    {
        if (IsAssetProcessed)
            return;
        IsAssetProcessed = true;

        if (assetPath.IndexOf("GameResource") < 0 || assetPath.IndexOf("@e") >= 0)
            return;

        TextureImporter textureImporter = (TextureImporter)assetImporter;
        if (textureImporter == null)
            return;
        textureImporter.textureType = TextureImporterType.Advanced;
        int width = 0;
        int height = 0;
        GetOriginalSize(textureImporter, out width, out height);
        if (!GetIsMultipleOf4(width) || !GetIsMultipleOf4(height))
        {
            Debug.LogError("4---" + assetPath);
        }
        bool IsPowerOfTwo = GetIsPowerOfTwo(width) && GetIsPowerOfTwo(height);
        if (!IsPowerOfTwo)
            textureImporter.npotScale = TextureImporterNPOTScale.None;

        textureImporter.mipmapEnabled = false;
        textureImporter.maxTextureSize = GetMaxSize(Mathf.Max(width,height));

        if (assetPath.EndsWith(".jpg"))
        {
            textureImporter.textureFormat = TextureImporterFormat.ETC2_RGB4;
        }
        else if (assetPath.EndsWith(".png"))
        {
            if (!textureImporter.DoesSourceTextureHaveAlpha())
                textureImporter.grayscaleToAlpha = true;
            textureImporter.alphaIsTransparency = true;
            textureImporter.textureFormat = TextureImporterFormat.ETC2_RGBA8;

            string atlasName = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(assetPath)).Name;
            if (atlasName.Equals("UI"))
            {
                textureImporter.spriteImportMode = SpriteImportMode.Single;
                textureImporter.spritePackingTag = "UI";
            }
        }
        else
        {
            Debug.Log("圖片格式---"+assetPath);
        }
    }

    /// <summary>
    /// 獲取texture的原始文件尺寸
    /// </summary>
    /// <param name="importer"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    void GetOriginalSize(TextureImporter importer, out int width, out int height)
    {
        object[] args = new object[2] { 0, 0 };
        MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
        mi.Invoke(importer, args);
        width = (int)args[0];
        height = (int)args[1];
    }

    bool GetIsMultipleOf4(int f)
    {
        return f % 4 == 0;
    }

    bool GetIsPowerOfTwo(int f)
    {
        return (f & (f - 1)) == 0;
    }

    int GetMaxSize(int longerSize)
    {
        int index = 0;
        for (int i = 0; i < maxSizes.Length; i++)
        {
            if (longerSize <= maxSizes[i])
            {
                index = i;
                break;
            }
        }
        return maxSizes[index];
    }
}
**有幾點需要說明一下:**
1. 在實際的使用中發現,OnPreprocessTexture()方法在每次更改圖片格式的時候都會執行,結果就是我們在導入圖片后就無法更改圖片的格式了。所以我們使用IsAssetProcessed屬性來記錄是否在導入時對圖片進行了設置。一旦設置過了,就不會對圖片進行處理了。
2. 最麻煩的就是獲取圖片的原始尺寸。還是在國外的論壇發現的方法,就是GetOriginalSize()方法,用來獲取圖片的原始尺寸。

工程地址:https://github.com/bzyzhang/TextureTool


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM