绘制到替代 RenderTarget2D 的问题,似乎绘制到后台缓冲区
本文关键字:绘制 后台 缓冲区 RenderTarget2D 问题 | 更新日期: 2023-09-27 18:32:34
因此,为了在旋转纹理后从纹理中获取 Color[] 数据,以便将此数据用于每像素碰撞,我使用以下方法将所述纹理(旋转(绘制到单独的 RenderTarget2D,然后将其转换回 texture2D 并从中获取颜色数据:
public Color[] GetColorDataOf(SpriteBatch spriteBatch, Texture2D texture, float rotation)
{
// Get boundingBox of texture after rotation
Rectangle boundingBox = GetEnclosingBoundingBox(texture, rotation);
// Create new rendertarget of this size
RenderTarget2D buffer = new RenderTarget2D(GraphicsDevice, boundingBox.Width, boundingBox.Height);
// Change spritebatch to new rendertarget
GraphicsDevice.SetRenderTarget(buffer);
// Clear new rendertarget
GraphicsDevice.Clear(Color.Transparent);
// Draw sprite to new rendertarget
spriteBatch.Draw(texture, new Rectangle(boundingBox.Width / 2, boundingBox.Height / 2, texture.Width, texture.Height), null, Color.White, rotation, new Vector2(boundingBox.Center.X, boundingBox.Center.Y), SpriteEffects.None, 1f);
// Change rendertarget back to backbuffer
GraphicsDevice.SetRenderTarget(null);
// Get color data from the rendertarger
Color[] colorData = new Color[boundingBox.Width * boundingBox.Height];
Texture2D bufferTexture = (Texture2D)buffer;
bufferTexture.GetData(colorData);
return colorData;
}
现在我有两个问题(我希望它们是链接的(,首先纹理被绘制在屏幕上,并且返回的所有 Color[] 数据都是空的(即所有字段都等于 0(。
**编辑**使用 Texture2D.SaveAsPng(( 我可以看到 bufferTexture 是正确的大小,但完全透明,表明问题在于绘制缓冲区。
所以我
修复了它。事实证明,我需要在我绘制到新渲染目标的位置创建另一组 SpriteBatch.Begin(( 和 SpriteBatch.End(( 调用,否则它只是绘制到后台缓冲区。