XNA based control for windows form application
Here is a class that I finally came up with. I would like to point everyone first to Shaggy Hiker's codebank suggestion here. He was the one who explained how to actually draw on the control.
As for the class:
Code:
Option Strict On
Option Explicit On
Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports System.IO
Public Class Xna_Sprite
Inherits Windows.Forms.Control
Private grafix As Graphics.GraphicsDevice
Private s_Batch As SpriteBatch
Private img As Bitmap
Public Property Image() As Bitmap
Get
Return img
End Get
Set(ByVal value As Bitmap)
img = value
Call Reset()
End Set
End Property
Private transColor As Color = Color.CornflowerBlue
Public Property TransparentColor() As Color
Get
Return transColor
End Get
Set(ByVal value As Color)
transColor = value
End Set
End Property
Private textur As Texture2D
Private Function initialize(ByRef surface As Xna_Sprite) 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
Private 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
Private Sub Load_Content()
If IsNothing(grafix) = False Then
s_Batch = New SpriteBatch(grafix)
textur = BitmapToTexture2D(grafix, img)
Else
Throw New ArgumentNullException("Grafix")
Exit Sub
End If
End Sub
Private Sub Draw()
grafix.Clear(transColor)
With s_Batch
.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend)
.Draw(textur, New Rectangle(0, 0, img.Width, img.Height), transColor)
.End()
End With
grafix.Present()
End Sub
Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
If IsNothing(img) Then
Dim g As Drawing.Graphics = e.Graphics
g.DrawIcon(System.Drawing.SystemIcons.Error, Me.DisplayRectangle)
Else
Call Reset()
End If
'MyBase.OnPaint(e)
End Sub
Public Sub Reset()
If initialize(Me) Then
Call Load_Content()
Call Draw()
End If
End Sub
End Class
For the initialize, bitmaptotexture2d, load_content, and draw please refer to my xna tutorials in the Utility Bank.