Fill a sprite using a pattern (getpixels32/setpixels32)

Hello everyone! I am trying to fill a sprite using a pattern.

The logic is this: I get all the colors of the main image as well as all the colors of the pattern image

currentColors
Color32[] patternColors = filTexture.GetPixels32();

Then I iterate through the color array of the main image, avoiding the black borders and changing the color based on the alpha of the pattern.

int patternPixelPosition = 0;
                int patternPixelLength = patternColors.Length;
                for (int i = 0; i < currentColors.Length; i++)
                {
                        if (!DrawUtils.CompareColor(currentColors[i], new Color32(0, 0, 0, 255))) // black border
                        {
                           
                            if (patternPixelPosition >= patternPixelLength)
                                patternPixelPosition = 0;

                            if (patternColors[patternPixelPosition].a > 0)
                                currentColors[i] = сurrentDrawingColor;
                            else
                                currentColors[i] = new Color32(255, 255, 255, 255);

                            patternPixelPosition+=1;
                           
                        }

                }

7548565--932968--11.png
in the end it turns out like this
How can I fill in without distortion?

You are filling the larger image using the same line stride as the sprite itself, but it (obviously) has a different stride.

You need to iterate the possible tiles within the target image, then within each one copy the pixels of the sprite, or alternately work the other way around. In other words, your blit code needs to be rectangle-aware at both the source and destination.

Think of filling a page with square postage stamps. Your approach is cutting the stamps into 1-pixel high strips of paper and laying them across the paper, only going to the next lower line on the paper when you reach the right edge.

You can probably do this easier (and much faster) using Graphics.Blit

1 Like

thanks, I think I understand now

1 Like

There’s a lot of reading to be had, such as this:

Shouldn’t be too hard to get what you want. Doing it pixel at a time will likely only be fast enough to do it at load time, not during the actual game running frame.