C# 从XNA 4.0中的RenderTarget2D对象获取纹理2D
我只是在试验像素着色器。我发现了一个很好的模糊效果,现在我正试图创造一个效果模糊图像一遍又一遍 方法:我想在渲染目标中应用模糊效果渲染我的图像hellokittyTexture,然后用该渲染的结果替换hellokittyTexture,并在每次绘制迭代中反复执行该操作:C# 从XNA 4.0中的RenderTarget2D对象获取纹理2D,c#,xna,rendering,pixel-shader,C#,Xna,Rendering,Pixel Shader,我只是在试验像素着色器。我发现了一个很好的模糊效果,现在我正试图创造一个效果模糊图像一遍又一遍 方法:我想在渲染目标中应用模糊效果渲染我的图像hellokittyTexture,然后用该渲染的结果替换hellokittyTexture,并在每次绘制迭代中反复执行该操作: protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue);
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的引用。基本上,它们是asignation之后的同一对象
您知道一种在RenderTarget中获取纹理的好方法吗?或者用一种更优雅的方式来做我想做的事
spriteBatch.Draw(hellokittyTexture , Vector2.Zero, Color.White);
在这行中,您正在绘制纹理。。。对自己。。。那是不可能的
假设buffer1和hellokittyTexture已正确初始化,请替换此行:
hellokittyTexture = (Texture2D) buffer1;
为此:
Color[] texdata = new Color[hellokittyTexture.Width * hellokittyTexture.Height];
buffer1.GetData(texdata);
hellokittyTexture.SetData(texdata);
这样,hellokittyTexture将被设置为buffer1的副本,而不是指向它的指针
在这行中,您正在绘制纹理。。。对自己。。。那是不可能的
假设buffer1和hellokittyTexture已正确初始化,请替换此行:
hellokittyTexture = (Texture2D) buffer1;
为此:
Color[] texdata = new Color[hellokittyTexture.Width * hellokittyTexture.Height];
buffer1.GetData(texdata);
hellokittyTexture.SetData(texdata);
这样,hellokittyTexture将被设置为buffer1的副本,而不是指向它的指针。只是对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);
只是对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);
renderTarget必须具有允许设置其纹理数据的字段、属性或方法,或者使用该字段、属性或方法,或者仅将纹理绘制到itrenderTarget必须具有允许设置其纹理数据的字段、属性或方法,或者使用该字段、属性或方法,或者仅将纹理绘制到iThanks mcmonkey!那就是我要找的。谢谢mcmonkey!这就是我一直在寻找的。如果你要这样做,打电话给hellokittyTexture.Dispose;在执行此操作之前,请确保它已从内存中删除;在执行此操作之前,请确保它已从内存中删除。