我想使用XNA在Windows Phone 7上绘制网格

时间:2011-06-04 03:21:58

标签: windows-phone-7 xna xna-4.0

我正在尝试在Windows Phone的屏幕上绘制网格;它可以帮助我更好地将我的精灵定位在屏幕上,而不是猜测屏幕上的位置。

我找到了几个使用XNA 3.0的网格(2d或3d)的例子,但遗憾的是架构不同,因此代码在XNA 4.0中不起作用

有没有人可以使用的东西?

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以在此处下载PrimitiveBatch课程http://create.msdn.com/en-US/education/catalog/sample/primitives并使用以下代码生成适当的网格作为纹理。

PrimitiveBatch primitiveBatch;
private Texture2D GenerateGrid(Rectangle destRect, int cols, int rows, Color gridColor, int cellSize)
{
    int w = (int)(cols * gridCellSize);
    int h = (int)(rows * gridCellSize);

    float uselessWidth = destRect.Width - w;
    float uselessHeigth = destRect.Height - h;

    Rectangle bounds = new Rectangle((int)(uselessWidth / 2) + destRect.X, (int)(uselessHeigth / 2) + destRect.Y, w, h);

    RenderTarget2D grid = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

    GraphicsDevice.SetRenderTarget(grid);
    GraphicsDevice.Clear(Color.Transparent);

    primitiveBatch.Begin(PrimitiveType.LineList);

    float x = bounds.X;
    float y = bounds.Y;

    for (int col = 0; col < cols + 1; col++)
    {
        primitiveBatch.AddVertex(new Vector2(x + (col * gridCellSize), bounds.Top), gridColor);
        primitiveBatch.AddVertex(new Vector2(x + (col * gridCellSize), bounds.Bottom), gridColor);
    }

    for (int row = 0; row < rows + 1; row++)
    {
        primitiveBatch.AddVertex(new Vector2(bounds.Left, y + (row * gridCellSize)), gridColor);
        primitiveBatch.AddVertex(new Vector2(bounds.Right, y + (row * gridCellSize)), gridColor);
    }
    primitiveBatch.End();

    GraphicsDevice.SetRenderTarget(null);
return grid;
}

答案 1 :(得分:1)

你能做到的一种快速而肮脏的方式(因为调试速度越快越好)就是简单地创建一个网格纹理,其分辨率与运行XNA游戏时相同(如果你正在运行)它与手机的分辨率相同,为480x800)。大多数纹理只是一个alpha贴图,并且有一个像素的网格线,你可以创建多个分辨率,或者你可以重复单个像素的小纹理交叉划分屏幕的一部分,该部分可以被你正在运行的分辨率整除在。

draw方法将如下所示,并称为everyframe。

此代码可以在游戏类中声明

Texture2D gridTexture;
Rectangle gridRectangle;

此代码应位于LoadContent方法

//Best to use something like a png file
gridTexture = content.Load<Texture2D>("pathto/mygridtexture");
gridRectangle = new Rectangle(0,0,resolutionX,resolutionY);

这个方法最后应该从你的Draw方法中调用,以确保它只是在顶部,假设你只是使用标准spriteBatch.Begin()来渲染精灵(如果你正在进行FrontToBack渲染,则首先)。

public void DrawGrid()
{
    spriteBatch.Draw(gridTexture, gridRectangle, Color.White);
}

此网格将在整个应用程序运行期间保持静止,并且在尝试排列您的UI或游戏中具有相对位置的对象时非常有用。

HTH。

答案 2 :(得分:1)

您可能需要查看XPF project by RedBadger。它使您能够在XNA项目中使用XAML样式布局。