Drawing an image using XNA in VB.Net-VBForums
Results 1 to 6 of 6

Thread: Drawing an image using XNA in VB.Net

  1. #1

    Thread Starter
    Hobbyist dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    3,904

    Drawing an image using XNA in VB.Net

    A few prerequisites:
    • Visual Basic.Net 2010 or higher
    • Microsoft XNA 4.0 or higher



    Following my prior tutorial, go ahead and add the correct XNA references and Import:
    1. Microsoft.Xna.Framework
    2. Microsoft.Xna.Framework.Graphics


    The first thing that we will do is declare three(3) variables:
    Code:
        Private grafix As Graphics.GraphicsDevice = Nothing
        Private s_Batch As SpriteBatch
        Private sprite As Texture2D
    The next step in our process is to start a boolean function. Now in this function, we will try to set up the graphics device. If for whatever reason we fail, in the form_load event an error will be thrown.
    Code:
        Private Function initialize(ByRef surface As PictureBox) As Boolean
            Try
                Dim pparam As New PresentationParameters
                pparam.DeviceWindowHandle = surface.Handle
                pparam.IsFullScreen = False
    
                Dim grafixAdapt As GraphicsAdapter = GraphicsAdapter.DefaultAdapter
    
                grafix = New GraphicsDevice(grafixAdapt, GraphicsProfile.HiDef, pparam)
    
    
                initialize = True
            Catch ex As Exception
                initialize = False
            End Try
        End Function
    I explained what that function does in the prior tutorial. The next step is to create a function that will return a texture2d.
    Code:
        Public Shared Function BitmapToTexture2D(GraphicsDevice As GraphicsDevice, image As System.Drawing.Bitmap) As Texture2D
            Dim bufferSize As Integer = image.Height * image.Width * 4
    
            Dim memoryStream As New System.IO.MemoryStream(bufferSize)
            image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png)
    
            memoryStream.Seek(0, SeekOrigin.Begin)
            Dim texture As Texture2D = Texture2D.FromStream(GraphicsDevice, memoryStream, image.Width, image.Height, False)
     
            memoryStream.Close()
            Return texture
        End Function
    This is important because XNA isn't intended to render bitmaps, it's intended to render texture2d's. Now the main method going on in that function is the Texture2d.FromStream. Now if you aren't paying attention to the prerequisites and using a former version of XNA I believe the method used is the Texture2d.FromFile, the parameters are a bit different, but the concepts the same.

    The next step is to actually convert the bitmap to a texture2d:
    Code:
        Private Sub Load_Content()
            If IsNothing(grafix) = False Then
                s_Batch = New SpriteBatch(grafix)
    
                sprite = BitmapToTexture2D(grafix, My.Resources.my_image)
            Else
                Throw New ArgumentNullException("Grafix")
                Exit Sub
            End If
    
        End Sub
    Finally we will use a backgroundworker to continually display our sprite:
    Code:
        Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Do Until True = False
                grafix.Clear(Color.CornflowerBlue)
    
                With s_Batch
                    .Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend)
                    .Draw(sprite, New Rectangle(0, 0, My.Resources.my_image.Width, My.Resources.my_image.Height), Color.CornflowerBlue)
                    .End()
                End With
    
                grafix.Present()
            Loop
        End Sub
    This is where all the action happens. The spritebatch.begin starts the whole process. The spritebatch.draw actually does the rendering. Finally the spritebatch.end brings the state of our device back to the state it was in before we called .Begin. You can think of spritebatch.end as FileStream.Close. The last thing we do is call graphicsdevice.Present, this actually shows the sprite. All in all in the end, it should look like this:

    Code:
    Option Strict On
    Option Explicit On
    
    Imports System.IO
    Imports Microsoft.Xna.Framework
    Imports Microsoft.Xna.Framework.Graphics
    Public Class Form1
        Private grafix As Graphics.GraphicsDevice = Nothing
        Private s_Batch As SpriteBatch
        Private sprite As Texture2D
    
        Private Function initialize(ByRef surface As PictureBox) As Boolean
            Try
                Dim pparam As New PresentationParameters
                pparam.DeviceWindowHandle = surface.Handle
                pparam.IsFullScreen = False
    
                Dim grafixAdapt As GraphicsAdapter = GraphicsAdapter.DefaultAdapter
    
                grafix = New GraphicsDevice(grafixAdapt, GraphicsProfile.HiDef, pparam)
    
    
                initialize = True
            Catch ex As Exception
                initialize = False
            End Try
        End Function
    
        Public Shared Function BitmapToTexture2D(GraphicsDevice As GraphicsDevice, image As System.Drawing.Bitmap) As Texture2D
            Dim bufferSize As Integer = image.Height * image.Width * 4
    
            ' Create new memory stream and save image to stream so    
            ' we don't have to save and read file   
            Dim memoryStream As New System.IO.MemoryStream(bufferSize)
            image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png)
    
            ' Creates a texture from IO.Stream - our memory stream
            memoryStream.Seek(0, SeekOrigin.Begin)
            Dim texture As Texture2D = Texture2D.FromStream(GraphicsDevice, memoryStream, image.Width, image.Height, False)
    
            memoryStream.Close()
            Return texture
        End Function
    
    
        Private Sub Load_Content()
            If IsNothing(grafix) = False Then
                s_Batch = New SpriteBatch(grafix)
    
                sprite = BitmapToTexture2D(grafix, My.Resources.my_image)
            Else
                Throw New ArgumentNullException("Grafix")
                Exit Sub
            End If
    
        End Sub
    
        Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Do Until True = False
                grafix.Clear(Color.CornflowerBlue)
    
                With s_Batch
                    .Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend)
                    .Draw(sprite, New Rectangle(0, 0, My.Resources.my_image.Width, My.Resources.my_image.Height), Color.CornflowerBlue)
                    .End()
                End With
    
                grafix.Present()
            Loop
        End Sub
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Dim bool As Boolean = initialize(PictureBox1)
    
            If bool = True Then
                Call Load_Content()
    
                BackgroundWorker1.RunWorkerAsync()
            Else
                MessageBox.Show("There was a problem initializing XNA.")
                Me.Close()
            End If
        End Sub
    End Class

  2. #2
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    23,241

    Re: Drawing an image using XNA in VB.Net

    So this will draw a bitmap to the form using XNA, right? I'm wondering what the point of the backgroundworker is? I wouldn't think you'd have to be redrawing continually unless something else is drawing over your image continually, which may be the case. To draw controls with XNA I had to suppress the paint event for the control as I didn't want GDI to be painting the control when I was painting it.
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    Hobbyist dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    3,904

    Re: Drawing an image using XNA in VB.Net

    What this does is it draw's a converted texture2d from a bitmap onto a picturebox using the 'game' loop. The reason I keep it in the backgroundworker is because of the 'game' flow concept. See in regular winform's the app assumes that everything stays the same until something is invoked, where as in game app's it assumes that everything is constantly changing. There was an article I read.... <waiting for google> .... When WinForms met the game loop that really helped me out that I think people should read when deciding when to use a 'game' loop and when to just draw in 'WinForm' fashion. So because I'm assuming that most people will visit this thread for game programming in xna I decided to keep it in a continuous loop, or the 'game' loop.

  4. #4
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    23,241

    Re: Drawing an image using XNA in VB.Net

    Ah, a game running in a window as opposed to a typical WinForms program that spends most of its time doing nothing.
    My usual boring signature: Nothing

  5. #5

    Thread Starter
    Hobbyist dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    3,904

    Re: Drawing an image using XNA in VB.Net

    Quote Originally Posted by Shaggy Hiker View Post
    Ah, a game running in a window as opposed to a typical WinForms program that spends most of its time doing nothing.
    Yep, that was the flow design idea behind these series of tutorials. Something I'd like to mention to those with aspirations of XBox programming is:

    A)You cannot port a vb.net xna game to XBox
    B)Even if you could, you wouldn't beable to use the BitmapToTexture2D because XBox wouldn't let you.

    Microsoft hasn't mentioned anything about allowing VB.Net/XNA games to be ported over to Xbox and to be honest I don't think they'll ever consider it. Reason being is because I'm assuming it would cost thousands of dollars to get Xbox to compile vb.net code.

  6. #6
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    23,241

    Re: Drawing an image using XNA in VB.Net

    That's kind of ironic, when you think about it. The point behind .NET, originally, was that various people would create JIT compilers for different platforms and you'd be able to take your IL and run it on different platforms. It was the idea behind JAVA, too. Therefore, it's a bit funny that MS decided not to create a JIT compiler for the only platform they totally own.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.