简体   繁体   中英

Get an array of each pixels color from Texture2D XNA?

I have a image that contains a layout for a level, and I want to load the level in the game by reading each pixels color from the image, and drawing the corresponding block. I am using this code:

public void readLevel(string path, GraphicsDevice graphics)
    {
        //GET AN ARRAY OF COLORS
        Texture2D level = Content.Load<Texture2D>(path);
        Color[] colors = new Color[level.Width * level.Height];
        level.GetData(colors);

        //READ EACH PIXEL AND DRAW LEVEL
        Vector3 brickRGB = new Vector3(128, 128, 128);

        int placeX = 0;
        int placeY = 0;

        foreach (Color pixel in colors)
        {
            SpriteBatch spriteBatch = new SpriteBatch(graphics);
            spriteBatch.Begin();

            if (pixel == new Color(brickRGB))
            {
                Texture2D brick = Content.Load<Texture2D>("blocks/brick");
                spriteBatch.Draw(brick, new Rectangle(placeX, placeY, 40, 40), Color.White);
            }


            if(placeX == 22)
            {
                placeX = 0;
                placeY++;
            }
            else 
            spriteBatch.End();
        }
    }

But it just shows a blank screen. Help would be appreciated!

EDIT: PROBLEM FIXED! (Read htmlcoderexe's answer below) Also, there was another problem with this code, read here.

Your code seems to draw each sprite at one pixel offset from the previous, but your other parameter suggests they are 40 pixel wide. placeX and placeY will need to be multiplied by the stride of your tiles (40).

Also, in the bit where you compare colours, you might be having a problem with floating point colour values (0.0f-1.0f) and byte colours being used together.

new Color(brickRGB)

This translates to:

new Color(new Vector3(128f,128f,128f))

So it tries constructing a colour from the 0.0f-1.0f range, clips it down to 1f (the allowed maximum for float input for Color), and you end up with a white colour (255,255,255), which is not equal to your target colour (128,128,128).

To get around this, try changing

 Vector3 brickRGB = new Vector3(128, 128, 128);

to

 Color brickRGB = new Color(128, 128, 128);

and this part

 if (pixel == new Color(brickRGB))

to just

if (pixel == brickRGB)

You will also need to create your drawing rectangle with placeX and placeY multiplied by 40, but do not write to the variable - just use placeX*40 for now and replace it with a constant later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM