Sometimes you need a simple progressbar in your XNA game to display game points, life, etc.
Lets do it quick and simple with rectangles only:
-One gray rectangle for the fix bar, and one red rectangle for the moving bar (use +/- keys).
-a very simple math formula to draw the current value against the width of the bar : progressbar_width * progressbar_value / progressbar_max
The sourcecode : Here
Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework.Audio
Imports Microsoft.Xna.Framework.Content
Imports Microsoft.Xna.Framework.Media
Imports Microsoft.Xna.Framework.Input
Public Class Game
Inherits Microsoft.Xna.Framework.Game
'Fields in our game graphic manager etc'
Dim graphics As GraphicsDeviceManager
Dim spritebatch As SpriteBatch
Dim dummyTexture As Texture2D
Dim progressbar_max = 100
Dim progressbar_value As Integer = progressbar_max
Dim progressbar_width As Integer = 250
Dim font As SpriteFont
Public Sub New()
graphics = New GraphicsDeviceManager(Me)
Window.Title = "Test"
graphics.PreferredBackBufferWidth = 400
graphics.PreferredBackBufferHeight = 200
End Sub
Protected Overrides Sub Initialize()
MyBase.Initialize()
End Sub
Protected Overrides Sub LoadContent()
spritebatch = New SpriteBatch(GraphicsDevice)
dummyTexture = New Texture2D(GraphicsDevice, 1, 1)
Dim c(0) As Color
c(0) = Color.White
dummyTexture.SetData(Of Color)(c)
'
font = Content.Load(Of SpriteFont)("xnb\myfont")
MyBase.LoadContent()
End Sub
Protected Overrides Sub UnloadContent()
MyBase.UnloadContent()
End Sub
Protected Overrides Sub Update(ByVal gameTime As Microsoft.Xna.Framework.GameTime)
If Keyboard.GetState.IsKeyDown(Keys.Add) Then progressbar_value += 1
If Keyboard.GetState.IsKeyDown(Keys.Subtract) Then progressbar_value -= 1
If progressbar_value >= progressbar_max Then progressbar_value = progressbar_max
If progressbar_value <= 0 Then progressbar_value = 0
MyBase.Update(gameTime)
End Sub
Protected Overrides Sub Draw(ByVal gameTime As Microsoft.Xna.Framework.GameTime)
GraphicsDevice.Clear(Color.Blue)
spritebatch.Begin()
spritebatch.DrawString(font, progressbar_value, New Vector2(10, 10), Color.White)
spritebatch.Draw(dummyTexture, New Rectangle(100, 10, progressbar_width, 10), Color.Gray)
spritebatch.Draw(dummyTexture, New Rectangle(100, 10, progressbar_width * progressbar_value / progressbar_max, 10), Color.Red)
spritebatch.End()
MyBase.Draw(gameTime)
End Sub
End Class