Unity 多图片(带透明通道)合成

取个巧,利用Camera和Render Texture
Unity 多图片(带透明通道)合成_第1张图片
多个2d图片组合成型
Unity 多图片(带透明通道)合成_第2张图片
每个Square都单独设置一个层级
Unity 多图片(带透明通道)合成_第3张图片
相机设置
Unity 多图片(带透明通道)合成_第4张图片
RenderTexture设置,然后将RenderTexture放在一个RawImage上

以下是生成图片的代码


using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class test2 : MonoBehaviour
{
    public RawImage rawImage;
    public RawImage rawImage2;
    void Start()
    {
        AAAAAA();
    }
    [ContextMenu("合成图片")]
    void AAAAAA()
    {
        Texture2D texture2D = TextureToTexture2D(rawImage2.texture);
        rawImage.texture = texture2D;
        rawImage.SetNativeSize();
        SavePicture(texture2D);

    }
    private Texture2D TextureToTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);

        return texture2D;
    }
    private void SavePicture(Texture2D texture2D)
    {
        byte[] bytes = texture2D.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件

        string filename = Application.dataPath + "/" + GetDateName() + ".png";

        FileInfo[] fileInfos = new DirectoryInfo(QuickConfig.instance._照片保存路径).GetFiles();
        for (int i = 0; i < fileInfos.Length; i++)
        {
            File.Delete(fileInfos[i].FullName);
        }
        System.IO.File.WriteAllBytes(filename, bytes);

        Debug.Log(string.Format("截屏了一张图片: {0}", filename, bytes));
    }
    /// 
    /// 获取以日期命名的名称
    /// 
    /// 日期命名
    public static string GetDateName()
    {
        int hour = DateTime.Now.Hour;
        int minute = DateTime.Now.Minute;
        int second = DateTime.Now.Second;
        int year = DateTime.Now.Year;
        int month = DateTime.Now.Month;
        int day = DateTime.Now.Day;
        return string.Format("{0:D4}{1:D2}{2:D2}{3:D2}{4:D2}{5:D2}", year, month, day, hour, minute, second);
    }
}

Unity 多图片(带透明通道)合成_第5张图片
左为相机看到的图,右为生成的图

你可能感兴趣的:(unity,游戏引擎)