【问题标题】:Getting a Texture2D from a RenderTarget2D object in XNA 4.0从 XNA 4.0 中的 RenderTarget2D 对象获取 Texture2D
【发布时间】:2013-07-10 08:19:55
【问题描述】:

我只是在尝试像素着色器。我发现了一个很好的模糊效果,现在我尝试创建一个反复模糊图像的效果。

我想怎么做:我想在 RenderTarget 中渲染我的图像 hellokittyTexture 应用模糊效果,然后用渲染结果替换 hellokittyTexture 并执行每次 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 中获取纹理的好方法吗?或更优雅的方式来做我正在尝试的事情?

【问题讨论】:

  • renderTarget 必须有一些允许设置其纹理数据的字段或属性或方法,要么使用它,要么只是将纹理绘制到它

标签: c# xna rendering pixel-shader


【解决方案1】:

只是对 McMonkey 答案的一点补充:

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

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

【讨论】:

  • 如果您要这样做,请在这样做之前致电hellokittyTexture.Dispose();,以确保将其从内存中删除。
【解决方案2】:
    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副本,而不是指向它的指针。

【讨论】:

  • 谢谢麦克蒙奇!那就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
  • 2012-12-21
  • 2017-02-14
相关资源
最近更新 更多