- Home /
Combine 2 textures of different sizes at specific location
Hi All,
I've seen several posts on combining textures and have some code that works although it does not work when I try to place a texture at a specific location on the background texture. What I'm trying to achieve is shown in the following image where the green rectangle (layer1) is centered on top of the black rectangle (layer0) and results in the image shown. What I get when I run this code is the green rectangle positioned against the left wall of the black rectangle. Code is below and any help would be very much appreciated.
public Texture2D MergeTextures(Texture2D background, Texture2D layer1)
{
int startX = 0;
int startY = 0;
Texture2D newTex = new Texture2D(background.width, background.height, background.format, false);
for (int x = 0; x < background.width; x++)
{
for (int y = 0; y < background.height; y++)
{
if (x >= startX && y >= startY && x < layer1.width && y < layer1.height)
{
Color bgColor = background.GetPixel(x, y);
Color wmColor = layer1.GetPixel(x - startX, y - startY);
Color final_color = Color.Lerp(bgColor, wmColor, wmColor.a / 1.0f);
newTex.SetPixel(x, y, final_color);
}
else
newTex.SetPixel(x, y, background.GetPixel(x, y));
}
}
newTex.Apply();
return newTex;
}
Answer by toddisarockstar · Oct 10, 2018 at 11:46 PM
the math for centering would be: subtract the layer size from the background and use half the result. do this for both width and height to get your start spot. also you forgot to add the start variable back to the right side of your less than statements. i made some untested adjustments but this should work for you
public Texture2D MergeTextures(Texture2D background, Texture2D layer1)
{
int startX = 0;
int startY = 0;
startX=background.width-layer1.width;
startX=(int)(startX*.5f);
startY=background.height-layer1.height;
startY=(int)(startY*.5f);
Texture2D newTex = new Texture2D(background.width, background.height, background.format, false);
for (int x = 0; x < background.width; x++)
{
for (int y = 0; y < background.height; y++)
{
if (x >= startX && y >= startY && x < layer1.width+startX && y < layer1.height+startY)
{
Color bgColor = background.GetPixel(x, y);
Color wmColor = layer1.GetPixel(x - startX, y - startY);
Color final_color = Color.Lerp(bgColor, wmColor, wmColor.a / 1.0f);
newTex.SetPixel(x, y, final_color);
}
else
newTex.SetPixel(x, y, background.GetPixel(x, y));
}
}
newTex.Apply();
return newTex;
}
Thank you @toddisarockstar ! It looks like you truly are a Rock Star. Really appreciate your help.
Your answer
Follow this Question
Related Questions
How to merge two textures of different size? 1 Answer
Texture2D update every frame - The right method 4 Answers
Fastest way to update Texture2D 0 Answers
Translate a pixel using SetPixel on a Texture2D? 1 Answer
Rotate Texture2d 1 Answer