2012-05-04 72 views
0

我想在XNA中使用spritefont在屏幕上繪製文本。 我可以讓文字出現,但無論我嘗試什麼,在繪製文字時總會出現其他問題。使用SpriteFont在XNA4中繪製文本時的問題

我想顯示FPS。 我已經嘗試了幾種不同的方式,並在我做的各種不同的XNA項目中嘗試過。 將文本繪製到屏幕時發生的一些事情包括 - 頂點被拉得更遠並且位置錯誤,頂點完全不能被繪製,線框模式無法打開。 只是取決於我如何嘗試呈現文本我總是以其中之一結束。 然後如果我註釋掉繪製文本的部分,一切都會恢復正常。

下面是在代碼的頂部一些代碼 我的變量 -

GraphicsDeviceManager graphics; 
    SpriteFont font; 
    SpriteBatch spriteBatch; 

在我LoadContent我有

 font = Content.Load<SpriteFont>("SpriteFont1"); 
     RasterizerState rs = new RasterizerState(); 
     rs.FillMode = FillMode.WireFrame; 
     GraphicsDevice.RasterizerState = rs; 
     spriteBatch = new SpriteBatch(GraphicsDevice); 

這裏是我的整個繪製方法 -

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

     effect.Parameters["View"].SetValue(cam.viewMatrix); 
     effect.Parameters["Projection"].SetValue(projectionMatrix); 
     effect.CurrentTechnique = effect.Techniques["Technique1"]; 
     effect.CurrentTechnique.Passes[0].Apply(); 
     GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Count, 0, indices.Length/3); 

     spriteBatch.Begin(); 
     spriteBatch.DrawString(font, frameRate.ToString(), new Vector2(1, 1), Color.Black); 
     spriteBatch.End(); 

     frameCounter++; 
     base.Draw(gameTime); 
    } 

這是我發現的最接近的方式,但由於某種原因,它使WIR無論我嘗試做什麼,eframe都不起作用,而且我確實需要線框。

編輯: 我在程序運行時調試了填充模式,並在使用sprite字體時由於某種原因將其設置爲固定。 我可以在頂點繪製之前的每一幀重置填充模式,但我真的寧願不必這樣做。

+0

很可能這個副本:http://stackoverflow.com/questions/4902494/xna-spritebatch-causing-problems-with-basiceffect –

+0

好了,所以spritebatch.Begin()自動改變一些事情。我認爲這是非常愚蠢的,但我想我只需要重新設置它們每幀... – Frobot

+0

SpriteBatch.Begin不,但DrawString的,這不愚蠢。你應該在繪製之前真正地設置你需要的狀態,那麼這些類型的東西就不是問題。 Shawn Hargreaves看到這篇博客:http://blogs.msdn.com/b/shawnhar/archive/2006/11/13/spritebatch-and-renderstates.aspx你應​​該閱讀所有Shawn的XNA博客文章。 –

回答

1

你應該只繪製財產以後贏線框模式之前使用您的光柵化狀態,不僅在負載方法......因爲batch.Begin()方法會設置一個默認的光柵化狀態

,如果你想使用其他光柵化狀態spritebatch,你應該提供一個

spritebatch.Begin(SortMode,...,,.., rs); 

你的代碼應該這樣改變:

static RasterizerState rs = new RasterizerState() { FillMode = FillMode.Wireframe; } 

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

    GraphicsDevice.RasterizerState = rs; 

    effect.Parameters["View"].SetValue(cam.viewMatrix); 
    effect.Parameters["Projection"].SetValue(projectionMatrix); 
    effect.CurrentTechnique = effect.Techniques["Technique1"]; 
    effect.CurrentTechnique.Passes[0].Apply(); 
    GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Count, 0, indices.Length/3); 
    .... 
+0

我其實有我的代碼工作幾乎完全相同的東西,所以我只是接受這個答案 – Frobot