5
\$\begingroup\$

I have an avatar generator where someone can create a custom avatar with layers superimposed. And in order to reuse this image multiple times, i want to merge all layers in one image. Is there any way on unity3D to create this image.

I've already coded that :

atlas = new Texture2D (width, height, TextureFormat.RGBA32, false);
foreach (Sprite s in allSprite) {
        atlas.SetPixels (0, 0, atlas.width, atlas.height, s.texture.GetPixels (0, 0, atlas.width, atlas.height));
        atlas.Apply ();
}

My problem is to keep the transparency and not erase old layers where pixels are transparent. The setPixels method replace old pixels in atlas by new one. I can't loop over pixels because of the size of the image (1024*1024) and more than 6 layers.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

You can use a RTT (render-to-texture) and a custom camera to one-shot render to it to merge all the layers using the GPU.

You can then save and use the resulting texture.

http://docs.unity3d.com/Manual/class-RenderTexture.html

If your render texture has alpha then it will maintain the composited alpha values as long as you use the proper separate color-alpha blending mode in the shaders:

Blend SrcAlpha OneMinusSrcAlpha, OneMinusDstAlpha One

If you only need full-size texture blending you can use graphic blit commands to get pixel-aligned full-texture blend (http://docs.unity3d.com/ScriptReference/Graphics.Blit.html)

Otherwise you'll need to draw pixel-aligned (http://docs.unity3d.com/ScriptReference/GL.LoadPixelMatrix.html) quads using the GL namespace functions (http://docs.unity3d.com/ScriptReference/GL.html)

\$\endgroup\$
5
  • \$\begingroup\$ With this method, i think the image will not keep their native resolution and the transparency will be lost. So it will not help me but it's a good approach i think, i'll try something like that \$\endgroup\$
    – Sata
    Jan 14, 2015 at 9:45
  • 2
    \$\begingroup\$ I added more information on how to achieve this with render textures. You will be able to keep the images native resolution and the transparency. \$\endgroup\$ Jan 14, 2015 at 15:41
  • \$\begingroup\$ I find a very helpfull code sample about doing this with RenderTexture here : link Thanks for helping me to find the right way do to it. \$\endgroup\$
    – Sata
    Jan 16, 2015 at 16:09
  • \$\begingroup\$ I meet with some graphic glitch in trying to use renderTexture on mac (link), i have already try to change the camera clear flags but it didn't work. So if you have any tips \$\endgroup\$
    – Sata
    Jan 28, 2015 at 8:27
  • \$\begingroup\$ Found solution using GL.Clear() to remove glitch. \$\endgroup\$
    – Sata
    Jan 29, 2015 at 14:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .