Unity3D研究院之静态合并贴图(一百一十六)

最近研究了一下Texture2D.PackTextures方法。它可以在运行时或者编辑时对贴图进行合并。运行时它不支持任意贴图格式的合并,比如现在主流的ASTC,它会合并成RGBA32格式。而且无法指定贴图合并到大图具体某个位置上。

动态合并贴图的方法可以参考我之前的文章,这篇主要考虑静态合并,也就是编辑模式下合并

Unity3D研究院之运行时合并ETC1、ETC2、ASTC、DXT1、DXT5、PVRTC贴图

既然是编辑模式下合并,我们肯定不希望每张小贴图也需要标记read/write enable 那样就太麻烦了。如下代码所示,提供需要合并的小图,以及小图所在大图的偏移即可。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

using System;

using System.IO;

using UnityEditor;

using UnityEngine;

 

public class TextureCombine

{

    [MenuItem("Tools/TextureCombine")]

    static void Combine()

    {

        Texture2D tex512 = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/512.jpg");

        Texture2D tex128 = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/128.jpg");

        Texture2D @out  = Combine(

            new[] { tex512, tex128 }, //贴图

            new[] { (0, 0), (600, 600) } //偏移

            ,1024);//最终贴图大小

 

        File.WriteAllBytes("Assets/out.jpg", @out.EncodeToJPG());

        AssetDatabase.Refresh();

    }

 

    static Texture2D Combine(Texture2D []texs, ValueTuple<int,int>[]offests,int size)

    {

        Texture2D @out = new Texture2D(size, size, TextureFormat.RGBA32, true);

        for (int i = 0; i < texs.Length; i++)

        {

            var tex = texs[i];

            var offest = offests[i];

            var width = tex.width;

            var height = tex.height;

            RenderTexture tmp = RenderTexture.GetTemporary(width,height,0,RenderTextureFormat.Default,RenderTextureReadWrite.Linear);

            Graphics.Blit(tex, tmp);

            RenderTexture previous = RenderTexture.active;

            RenderTexture.active = tmp;

            Texture2D @new = new Texture2D(width, height);

            @new.ReadPixels(new Rect(0, 0, width, height), 0, 0);

            @new.Apply();

            @out.SetPixels(offest.Item1, offest.Item2, width, height, @new.GetPixels());

            RenderTexture.active = previous;

            RenderTexture.ReleaseTemporary(tmp);

        }

        return @out;

    }

  

}

最后合并的结果

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值