Reputation: 2509
I'm trying to create a function within a class that will draw a playing card. I'm still getting to grips with Drawing in Winforms, so bear with me.
The basic class so far looks like this:
Public Class Card
Public Suit As Char
Public Value As String
Public Sub New(_Suit As Char, _Value As String)
Suit = _Suit
Value = _Value
End Sub
Public Sub Draw()
End Sub
End Class
Within the Card class, I want to create a sub Draw which draws a white rectangle, adds the number, suit symbol, etc. I've got the code that will draw a white rectangle, but I don't know how to adapt it to use inside a class. All I have is this eventhandler:
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
Dim p As Pen
p = New Pen(Color.Black, 2)
Dim rekt = New Rectangle(New Point(10, 10), New Size(90, 126))
Me.CreateGraphics.DrawRectangle(p, rekt)
CreateGraphics.FillRectangle(Brushes.White, rekt)
End Sub
This creates a white rectangle automatically when the Form loads. When I C&P the code in this eventhandler into the Draw function, it doesn't work, because CreateGraphics isn't a member of the Card class.
Is there a simple fix for this, or should I be approaching this fundamentally diferently?
Upvotes: 1
Views: 593
Reputation: 38865
It would be much easier to load pre-done images from an imagelist, so the the appropriate image can just be another Card
property. Otherwise you could get into things like drawing Heart and Club shapes (or changing fonts to use WebDings or perhaps a CardFace font or also drawing a bitmap of the suit symbol).
Your cards can draw themselves though, but you want to use the Graphics
object which Windows provides in the paint event:
myCard = New Card("Diamonds", 6)
Private Sub pb_Paint(sender As Object, e As PaintEventArgs) Handles pb.Paint
myCard.Draw(e.Graphics)
End Sub
e
is the PaintEventArgs
passed to you in the paint event. Its a class and one of the members is a Graphics
object. Card.Draw()
method:
Public Sub Draw(g As Graphics)
Dim br As Brush = Brushes.Black
If Suit.ToLowerInvariant = "hearts" Or Suit.ToLowerInvariant = "diamonds" Then
br = Brushes.Red
End If
Using p As New Pen(Color.Black, 2)
Dim rekt = New Rectangle(New Point(10, 10), New Size(90, 126))
g.DrawRectangle(p, rekt)
g.FillRectangle(Brushes.White, rekt)
Using f As New Font("Verdana", 16, FontStyle.Bold)
g.DrawString(Rank.ToString & " " & Suit(0), f, br, New Point(12, 12))
End Using
End Using
End Sub
Output (very crude!):
Notice also that I am disposing of the Pen
created. And in case it needs explaining Suit(0)
indicates the first character of the string.
Upvotes: 1