# XNA draw texture/font and DrawIndexedPrimitives at the same time [duplicate]

When i Draw a texture2d or a font with spriteBatch and also draw GraphicsDevice.DrawIndexedPrimitives, the frame is draw weird

SpriteBatch  spriteBatch = new SpriteBatch(GraphicsDevice);
BasicEffect basicEffect = new BasicEffect(GraphicsDevice);

protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.LightSteelBlue);
RasterizerState rasterizerState = new RasterizerState();
rasterizerState.CullMode = CullMode.None;
GraphicsDevice.RasterizerState = rasterizerState;

//for(...) {
GraphicsDevice.SetVertexBuffer(vertexBuffer);
GraphicsDevice.Indices = indexBuffer;

foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 20);
}
// } end for

spriteBatch.Begin();
spriteBatch.DrawString(MainFont, "FPS: " + Math.Round(1 / (float)gameTime.ElapsedGameTime.TotalSeconds, 2), new Vector2(200, 10), Color.Red);
spriteBatch.End();


How can i solve this ?

• @SethBattin i am already using spriteBatch.Begin(); / spriteBatch.End(); outside of the DrawIndexedPrimitives, that answer doesn't apply to my situation, at least i don't think it does ? the guy on the quiestion you linked me had Begin() in the very first line, and then End() at the last line, my case is different here – dimitris93 Jan 24 '15 at 23:27
• That linked question may be too succinct. In any case, the answer you already selected is correct, that is the cause of the problem. I also had trouble finding a good match when I searched. – Seth Battin Jan 25 '15 at 0:39

This is because the sprite batch hijacks the graphics device's states when you use it. You need to cache them before using the sprite batch and then restore them afterwards. (Or you can set them directly afterwards without caching if you know the ones you want to use.)

// cache device states
var blendState = GraphicsDevice.BlendState;
var depthStencilState = GraphicsDevice.DepthStencilState;
var samplerState = GraphicsDevice.SamplerStates[0];

// use your SpriteBatch

// restore device states
GraphicsDevice.BlendState = blendState;
GraphicsDevice.DepthStencilState = depthStencilState;
GraphicsDevice.SamplerStates[0] = samplerState;