kingBook

导航

Unity Editor 保存图片、缩放纹理

using System.IO;
using UnityEditor;
using UnityEngine;

public class ConvertIconToMultipleSizes : Editor {
    [MenuItem("Assets/Convert Icon To Multiple Sizes", true)]
    private static bool ValidateSplitFbxAnimation() {
        if (Selection.count == 1) {
            if (Selection.activeObject is Texture2D) {
                return true;
            }
        }
        return false;
    }

    [MenuItem("Assets/Convert Icon To Multiple Sizes")]
    private static void SplitFbxAnimation() {
        if (Selection.count == 1) {
            if (Selection.activeObject is Texture2D) {
                Texture2D source = Selection.activeObject as Texture2D;
                string sourcePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);

                Texture2D result = ScaleTexture(source, 36, 36);
                byte[] bytes = result.EncodeToPNG();

                string sourceFolderPath = Path.GetDirectoryName(sourcePath).Replace("\\", "/");
                string newFolderPath = sourceFolderPath + "/Icons";

                if (!File.Exists(newFolderPath)) {
                    Directory.CreateDirectory(newFolderPath);
                }

                string outputPath = $"{newFolderPath}/icon36x36.png";
                File.WriteAllBytes(outputPath, bytes);
                AssetDatabase.Refresh();
            }
        }
    }


    /// <summary>
    /// 缩放纹理
    /// <para>
    /// 注意:
    /// source 源纹理的 Read/Write 开关需要在 Inspector 中打开,
    /// 不能勾选 Use Crunch Compression
    /// </para>
    /// </summary>
    public static Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight) {
        Texture2D result = new(targetWidth, targetHeight);
        Color[] rpixels = new Color[targetWidth * targetHeight];
        float incX = ((float)1 / source.width) * ((float)source.width / targetWidth);
        float incY = ((float)1 / source.height) * ((float)source.height / targetHeight);
        for (int px = 0; px < rpixels.Length; px++) {
            rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * (Mathf.Floor((float)px / targetWidth)));
        }
        result.SetPixels(rpixels, 0);
        result.Apply();
        return result;
    }
}

posted on 2024-08-16 16:03  kingBook  阅读(5)  评论(0编辑  收藏  举报