Skip to main content
 首页 » 编程设计

c#之如何将字符绘制到 Texture2D

2024年02月23日16shihaiming

在 C# XNA 中,如何将单个字符绘制到 Texture2D 而不是 Sprite 批处理上?我希望这样做是为了用字符 char\background 数据填充 bool[,] 以分析其形状。

请您参考如下方法:

您可以使用渲染目标。基本思想不是将文本渲染到后台缓冲区,而是渲染到一个单独的缓冲区,然后它可以为您提供 Texture2D。

参见此处:http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.rendertarget(v=xnagamestudio.31).aspx

提问者编辑:

经许可,我已添加到此答案中。在撰写本文时,MSDN 上的信息已经过时,看起来比实际需要的更复杂,因此我编写了自己的示例来说明如何执行此操作。

完成此操作的类可能必须继承自 IDisposable 并实现不执行任何操作的 void Dispose()。

PresentationParameters pp = graphicsDevice.PresentationParameters; 
byte width = 20, height = 20; // for example 
 
// pp.BackBufferWidth, pp.BackBufferHeight // for auto x and y sizes 
RenderTarget2D render_target = new RenderTarget2D(graphicsDevice, 
width, height, false, pp.BackBufferFormat, pp.DepthStencilFormat, 
pp.MultiSampleCount, RenderTargetUsage.DiscardContents); 
 
graphicsDevice.SetRenderTarget(render_target); 
graphicsDevice.Clear(...); // possibly optional 
spriteBatch.Begin(); 
// draw to the spriteBatch 
spriteBatch.End(); 
graphicsDevice.SetRenderTarget(null); // Otherwise the SpriteBatch can't 
// be used as a texture, this may also need to be done before using the 
// SpriteBatch normally again to render to the screen. 
 
// render_target can now be used as a Texture2D 

在这一点上这可能会有用。 http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Texture_to_Colors.php