zoukankan      html  css  js  c++  java
  • 导入图片时设置默认格式

    当我们将图片导入到工程中时,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
  • 相关阅读:
    Android View 的绘制流程
    Android Studio 注释模板
    Flutter https://flutter.cn/docs学习之 工作原理
    Android 手机兼容差异
    Flutter plugin的两种方式
    本周总结
    mapreduce程序开发简单实例 WordCount
    《需求工程——软件建模与分析》阅读笔记之一
    本周总结
    本周总结
  • 原文地址:https://www.cnblogs.com/bzyzhang/p/7189785.html
Copyright © 2011-2022 走看看