114 lines
3.1 KiB
C#
114 lines
3.1 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using System.IO;
|
|
|
|
public class AdvancedImageBlender : MonoBehaviour
|
|
{
|
|
[Header("基础设置")]
|
|
public Image imageA;
|
|
public Image imageB;
|
|
public Shader blendShader;
|
|
|
|
[Header("颜色调整")]
|
|
public Color colorA = Color.white;
|
|
public Color colorB = Color.white;
|
|
|
|
[Header("导出设置")]
|
|
public string fileName = "ColorBlend_Result";
|
|
public string savePath = "Exports";
|
|
|
|
private Material blendMaterial;
|
|
|
|
void Start()
|
|
{
|
|
// 自动初始化材质
|
|
if (blendShader) blendMaterial = new Material(blendShader);
|
|
}
|
|
|
|
[ContextMenu("执行颜色混合导出")]
|
|
public void ExecuteColorBlendExport()
|
|
{
|
|
if (blendShader) blendMaterial = new Material(blendShader);
|
|
// 获取带颜色的纹理
|
|
Texture2D texA = GetColoredTexture(imageA, colorA);
|
|
Texture2D texB = GetColoredTexture(imageB, colorB);
|
|
|
|
// 创建临时RenderTexture
|
|
RenderTexture rt = CreateRenderTexture(texA);
|
|
|
|
// 设置材质参数
|
|
blendMaterial.SetTexture("_MainTex", texA);
|
|
blendMaterial.SetTexture("_BlendTex", texB);
|
|
blendMaterial.SetColor("_MainColor", colorA);
|
|
blendMaterial.SetColor("_BlendColor", colorB);
|
|
|
|
// 执行混合
|
|
Graphics.Blit(null, rt, blendMaterial);
|
|
|
|
// 保存结果
|
|
SaveResult(rt);
|
|
|
|
// 清理资源
|
|
CleanupResources(texA, texB, rt);
|
|
}
|
|
|
|
Texture2D GetColoredTexture(Image image, Color color)
|
|
{
|
|
// 获取原始纹理
|
|
Texture2D originTex = image.sprite.texture;
|
|
|
|
// 创建临时纹理
|
|
Texture2D coloredTex = new Texture2D(
|
|
originTex.width,
|
|
originTex.height,
|
|
originTex.format,
|
|
false
|
|
);
|
|
|
|
// 应用颜色
|
|
Color[] pixels = originTex.GetPixels();
|
|
for (int i = 0; i < pixels.Length; i++)
|
|
{
|
|
pixels[i] = pixels[i] * color;
|
|
}
|
|
coloredTex.SetPixels(pixels);
|
|
coloredTex.Apply();
|
|
|
|
return coloredTex;
|
|
}
|
|
|
|
RenderTexture CreateRenderTexture(Texture2D referenceTex)
|
|
{
|
|
return new RenderTexture(
|
|
referenceTex.width,
|
|
referenceTex.height,
|
|
24,
|
|
RenderTextureFormat.ARGB32
|
|
);
|
|
}
|
|
|
|
void SaveResult(RenderTexture rt)
|
|
{
|
|
Texture2D output = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
|
|
RenderTexture.active = rt;
|
|
output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
|
|
output.Apply();
|
|
|
|
byte[] bytes = output.EncodeToPNG();
|
|
string fullPath = Path.Combine(Application.streamingAssetsPath, savePath, fileName + ".png");
|
|
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
|
|
File.WriteAllBytes(fullPath, bytes);
|
|
|
|
Debug.Log($"导出成功:{fullPath}");
|
|
DestroyImmediate(output);
|
|
}
|
|
|
|
void CleanupResources(params UnityEngine.Object[] resources)
|
|
{
|
|
foreach (var obj in resources)
|
|
{
|
|
if (obj != null) DestroyImmediate(obj);
|
|
}
|
|
Resources.UnloadUnusedAssets();
|
|
}
|
|
} |