从XNA 4.0中的RenderTarget2D对象获取Texture2D

本文关键字:对象 获取 Texture2D RenderTarget2D 中的 XNA | 更新日期: 2023-09-27 18:21:58

我只是在尝试像素着色器。我发现了一个很好的模糊效果,现在我正试图创造一个模糊图像的效果,一遍又一遍。

我想怎么做:我想在应用模糊效果的RenderTarget中渲染我的图像hellokittyTexture,然后用该渲染的结果替换ellokitty纹理并在每次Draw迭代中反复渲染:

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

        GraphicsDevice.SetRenderTarget(buffer1);
        // Begin the sprite batch, using our custom effect.
        spriteBatch.Begin(0, null, null, null, null, blur);
        spriteBatch.Draw(hellokittyTexture , Vector2.Zero, Color.White);
        spriteBatch.End();
        GraphicsDevice.SetRenderTarget(null);
        hellokittyTexture = (Texture2D) buffer1;
        // Draw the texture in the screen
        spriteBatch.Begin(0, null, null, null, null, null);
        spriteBatch.Draw(hellokittyTexture , Vector2.Zero, Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }

但我得到了这个错误"当渲染目标用作纹理时,不能在设备上设置它。"因为hellokittyTexture = (Texture2D) buffer1;不是复制纹理,而是复制对RenderTarget的引用(基本上,它们在签名后是同一个对象)

你知道在RenderTarget中获取纹理的好方法吗?还是一种更优雅的方式来做我正在尝试的事情?

从XNA 4.0中的RenderTarget2D对象获取Texture2D

    spriteBatch.Draw(hellokittyTexture , Vector2.Zero, Color.White);

在这行中,你正在绘制纹理。。。对自己。。。这不可能发生。

假设buffer1hellokittyTexture已正确初始化,则替换此行:

    hellokittyTexture = (Texture2D) buffer1;

这个:

        Color[] texdata = new Color[hellokittyTexture.Width * hellokittyTexture.Height];
        buffer1.GetData(texdata);
        hellokittyTexture.SetData(texdata);

这样,hellokittyTexture将被设置为buffer1副本,而不是指向它的指针。

只是McMonkey答案的一小部分:

我得到了这个错误:"当资源在GraphicsDevice上活动设置时,您可能无法调用它。在调用SetData之前,请从设备中取消设置。"我通过创建一个新的纹理来解决这个问题。不知道这是否是性能问题,但它现在正在工作:

        Color[] texdata = new Color[buffer1.Width * buffer1.Height];
        buffer1.GetData(texdata);
        hellokittyTexture= new Texture2D(GraphicsDevice, buffer1.Width, buffer1.Height);
        hellokittyTexture.SetData(texdata);