Sora Sora - 7 days ago 5
C# Question

Merging two different texture into one in unity3d

i am trying to merge two textures into one in unity
the first texture is from a

webcamTexture

the second is from a sprite using :
gameobject.getComponent<SpriteRenderer>().sprite.texture as Texture2D


I'm having problem in writing the function this is what i did so far :

public static Texture2D CombineTextures(GameObject obj, Texture2D background, Texture2D TodrawLogo)
{
Vector3 v = obj.transform.position;// obj is TodrawLogo gameobject
int width = TodrawLogo.width;
int height = TodrawLogo.height;
for (int x =(int)v.x; x < width; x++){
background.SetPixel(x,(int)v.y,TodrawLogo.GetPixel(x,(int)v.y));
}
background.Apply();
return background;
}


this what i am trying to do :

WebcamTexture
enter image description here

the result Texture should be like this
enter image description here

the webcamTexture is a
3dplane
and the logo is a
single sprite

but sadly my function doesn't work
does anyone know how to fix this
I know that i should find the exact coordinate of the
todraw image
and set the pixels but i can't figure out how

Much appreciation

EDIT:

i tried to use @nexx code :

public static Texture2D CombineTexture(Texture2D background, Texture2D TodrawLogo)
{

int width = TodrawLogo.width;
int height = TodrawLogo.height;

int backWidth = background.width;
int backHeight = background.height;
// bottom right corner
int startX = backWidth - width;
int startY = backHeight - height;

// loop through texture
int y = 0;
while (y < backHeight) {
int x = 0;
while (x < backWidth) {
// set normal pixels
background.SetPixel(x,y,background.GetPixel(x,y));
// if we are at bottom right apply logo
//TODO also check alpha, if there is no alpha apply it!
if(x >= startX && y < backHeight- startY)
background.SetPixel(x,y,TodrawLogo.GetPixel(x-startX,y-startY));
++x;
}
++y;
}
background.Apply();
return background;
}


but this is the resulting image i get :
enter image description here

i am stuck at this can someone please tell me what am i doing wrong ?

Answer

Here's a working example. I tested!

public Texture2D AddWatermark(Texture2D background, Texture2D watermark)
{

    int startX = 0;
    int startY = background.height - watermark.height;

    for (int x = startX; x < background.width; x++)
    {

        for (int y = startY; y < background.height; y++)
        {
            Color bgColor = background.GetPixel(x, y);
            Color wmColor = watermark.GetPixel(x - startX, y - startY);

            Color final_color = Color.Lerp(bgColor, wmColor, wmColor.a / 1.0f);

            background.SetPixel(x, y, final_color);
        }
    }

    background.Apply();
    return background;
}
Comments