using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public RawImage sourceRawImage;
public RawImage targetRawImage;
void Start()
{
// 确保两个RawImage组件的纹理都已设置
if (sourceRawImage.texture is Texture2D sourceTex && targetRawImage.texture is Texture2D targetTex)
{
Texture2D resultTex = TransferColors(sourceTex, targetTex);
if (resultTex != null)
{
// 显示结果
targetRawImage.texture = resultTex;
}
}
}
private Texture2D TransferColors(Texture2D sourceTex, Texture2D targetTex)
{
if (sourceTex.width != targetTex.width || sourceTex.height != targetTex.height)
{
Debug.LogError("源图像和目标图像的尺寸必须相同");
return null;
}
// 创建新的目标纹理
Texture2D resultTex = new Texture2D(targetTex.width, targetTex.height, TextureFormat.RGBA32, false);
// 获取源图像和目标图像的像素数据
Color[] sourcePixels = sourceTex.GetPixels();
Color[] targetPixels = targetTex.GetPixels();
// 进行颜色传输
Color[] resultPixels = new Color[targetPixels.Length];
for (int i = 0; i < targetPixels.Length; i++)
{
// 保留目标图像的透明区域
if (targetPixels[i].a == 0)
{
resultPixels[i] = targetPixels[i]; // 透明区域保持原样
}
else
{
// 将源图像的颜色传输到目标图像,只有在源图像的像素不透明的情况下
if (sourcePixels[i].a > 0) // 源图片的透明度大于0
{
resultPixels[i] = sourcePixels[i]; // 将源图像的颜色赋值给目标图像
}
else
{
resultPixels[i] = targetPixels[i]; // 保留目标图像原有颜色
}
}
}
resultTex.SetPixels(resultPixels);
resultTex.Apply();
return resultTex;
}
}