如何绘制2D逐像素XNA?像素、XNA

2023-09-07 13:52:45 作者:平底锅大王

我想在屏幕上绘制逐像素使用XNA,但我有问题的资源。我认为最好的办法是将有1纹理更新每一帧,但我无法进行更新。这是我有这么远,只是作为一个测试:

I'm trying to draw on the screen pixel-by-pixel using XNA, but am having problems with resources. I thought the best way would be to have 1 texture that updates every frame, but I'm having trouble updating it. Here's what I've got so far, just as a test:

Texture2D canvas;
Rectangle tracedSize;
UInt32[] pixels;

protected override void Initialize()
    {
        tracedSize = GraphicsDevice.PresentationParameters.Bounds;
        canvas = new Texture2D(GraphicsDevice, tracedSize.Width, tracedSize.Height, false, SurfaceFormat.Color);
        pixels = new UInt32[tracedSize.Width * tracedSize.Height];               

        base.Initialize();
    }

protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        pixels[100] = 0xFF00FF00;
        canvas.SetData<UInt32>(pixels, 0, tracedSize.Width * tracedSize.Height);

        spriteBatch.Begin();
        spriteBatch.Draw(canvas, new Rectangle(0, 0, tracedSize.Width, tracedSize.Height), Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }

当绘图()被称为第二次,我得到以下错误:

When Draw() is called the second time, I get the following error:

的操作被中止。您不得修改已设置的设备上的资源,或者后它已被平铺括号内使用。

"The operation was aborted. You may not modify a resource that has been set on a device, or after it has been used within a tiling bracket."

如果我试图在抽奖()一个新的Texture2D,我很快得到了内存不足的错误。这是为Windows Phone。好像我试图做了错误的方式,我有什么其他选择,使其工作?

If I try to make a new Texture2D in Draw(), I quickly get an out of memory error. This is for Windows Phone. It seems like I'm trying to do it the wrong way, what other options do I have to make it work?

推荐答案

尝试设置 GraphicsDevice.Textures [0] = NULL 调用SetData的面前。根据你以后可能会有一个更高性能的方法的效果,你也可以考虑Silverlights WriteableBitmap的。

Try setting GraphicsDevice.Textures[0] = null before you call SetData. Depending on the effect you're after there may be a more performant method, you could also consider Silverlights WriteableBitmap.

编辑:这是code我在模拟器中进行测试:

This is the code I tested in the emulator:

Texture2D canvas;
Rectangle tracedSize;
UInt32[] pixels;

protected override void Initialize()
{
    tracedSize = GraphicsDevice.PresentationParameters.Bounds;
    canvas = new Texture2D(GraphicsDevice, tracedSize.Width, tracedSize.Height, false, SurfaceFormat.Color);
    pixels = new UInt32[tracedSize.Width * tracedSize.Height];

    base.Initialize();
}
Random rnd = new Random();
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    GraphicsDevice.Textures[0] = null;
    pixels[rnd.Next(pixels.Length)] = 0xFF00FF00;
    canvas.SetData<UInt32>(pixels, 0, tracedSize.Width * tracedSize.Height);

    spriteBatch.Begin();
    spriteBatch.Draw(canvas, new Rectangle(0, 0, tracedSize.Width, tracedSize.Height), Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}