Question

I am using the more manual method of drawing objects in Visual basic, with code such as:

  Dim g As Graphics = spritePanel.CreateGraphics
  g.Clear(Color.Black)

  Dim m As Matrix = New Matrix
  m.RotateAt(45, New Point(currentSprite.Left + currentSprite.width / 2 + 16, 
                           currentSprite.Top + currentSprite.height / 2 + 16))
  g.Transform = m

  g.DrawRectangle(New Pen(Brushes.Red, 3), 
                  New Rectangle(currentSprite.Left - 2,  
                                currentSprite.Top - 2, 35, 35))

The problem is that I'm trying to create a function to perform the m.rotateAt() method in a more general manner, because calculating the midpoint and putting it into the function call over and over will become tedious, and I want to rotate multiple types of object (images, strings, rectangles, ellipses etc). I figured something like:

Public Function SpinObject(angle As Single, thing As Object) As Matrix

However Object obviously doesn't have .left / .top / .width / .height as properties, so even though I can pass literally anything into this function, I can't actually access the data I need to calculate the matrix. I was looking for something like a "DrawableObject" mainly.

What this boils down to, is how can I create this function? I can't find a common base class for all the things I want to do. I think I could use

thing is typeof Rectangle

or similar for each type I want to work with, but I suspect there's a better way, but can't find it.

I am not very familiar with templates and generics but I suspect they may be part of the solution.

Was it helpful?

Solution

Make a class for each object you want to use - these all inheriting from a base class - this way you can have a method or collection use any of these objects, the base class implements an Interface with the Sub routine Rotate that takes the angle parameter. Now the function can take any of these objects then ask each object to rotate based on their internal method Rotate which handles the object in question and with it's specific way of rotating the object. You could even pass the graphics object to it for some simplicity.

'base class
Public MustInherit Class BaseObject : Implements IRotateObject
  Sub Rotate(angle As Single) Implements IRotateObject.Rotate
   'empty sub here, handle each in there Overload
  End Sub
End Class

'interface 
Public Interface IRotateObject
  Sub Rotate(angle As Single)
End Interface

'drawing object class
Public Class sprite : Inherits BaseObject
 Overloads Sub Rotate(angle As Single)
   'handle rotation for this object here
  End Sub
End Class

'usage
Dim collection As New List(Of BaseObject)
Dim _sprite As New sprite
collection.Add(_sprite)

For Each obj In collection
  obj.Rotate(45)
Next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top