在像素颜色上绘制精灵

时间:2012-11-28 15:37:13

标签: c# colors xna sprite pixel

我用简单的磁贴引擎做了一个小游戏,它绘制了一个与.txt文件中的数字对应的精灵。现在我想要进步,我想让游戏读取一个.png或者什么,并且对于每个像素,它都会绘制一个精灵。并且在图像中使用不同的颜色,可以绘制不同的精灵。有人可以帮我弄这个吗?另外,我在C#XNA 4.0中这样做。

2 个答案:

答案 0 :(得分:1)

首先,使用管道将图像加载到Texture2D中。然后在你的代码中使用texture2d.GetData来获取像素的颜色。

MSDN texture2d.GetData示例http://msdn.microsoft.com/en-us/library/bb197093.aspx

答案 1 :(得分:1)

使用Texture2D.GetData可能会很棘手,如果您使用它来制作图块地图(我假设地图将是瓷砖的2D网格),因为Texture2D。GetData会返回一维数组。

首先,你需要你的数组用于地图,但是你存储它可能看起来像这样:

Color[,] tiles = new Color[LEVEL_WIDTH,LEVEL_HEIGHT];

我使用以下技术从文件中加载预制结构

//Load the texture from the content pipeline
Texture2D texture = Content.Load<Texture2D>("Your Texture Name and Directory");

//Convert the 1D array, to a 2D array for accessing data easily (Much easier to do Colors[x,y] than Colors[i],because it specifies an easy to read pixel)
Color[,] Colors = TextureTo2DArray(texture);

功能......

    Color[,] TextureTo2DArray(Texture2D texture)
    {
        Color[] colors1D = new Color[texture.Width * texture.Height]; //The hard to read,1D array
        texture.GetData(colors1D); //Get the colors and add them to the array

        Color[,] colors2D = new Color[texture.Width, texture.Height]; //The new, easy to read 2D array
        for (int x = 0; x < texture.Width; x++) //Convert!
            for (int y = 0; y < texture.Height; y++)
                colors2D[x, y] = colors1D[x + y * texture.Width];

        return colors2D; //Done!
    }

现在您可能想要将地图设置为颜色,只需执行tiles = Colors,您就可以使用Colors[x,y]轻松访问数组中的数据!

示例:

 using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace YourNameSpace
{
    class Game
    {
        //"Global" array for the map, this holds each tile
        Color[,] tiles = new Color[LEVEL_WIDTH, LEVEL_HEIGHT];
        protected override void Initialize() //OR wherever you load the map and stuff
        {
            //Load the texture from the content pipeline
            Texture2D texture = Content.Load<Texture2D>("Your Texture Name and Directory");

            //Convert the 1D array, to a 2D array for accessing data easily (Much easier to do Colors[x,y] than Colors[i],because it specifies an easy to read pixel)
            Color[,] Colors = TextureTo2DArray(texture);
        }
        Color[,] TextureTo2DArray(Texture2D texture)
        { //ADD THE REST, I REMOVED TO SAVE SPACE
        }
    }
}