Changing the color of a pen

  • Thread starter Thread starter mark blackall
  • Start date Start date
M

mark blackall

Hi all,

I can see how to change the color of a pen in VB.net, but how would I change
the color randomly? I guess it would have to be some way of accessing the
color by a number, rather than its name.

Thanks

Mark
 
One approach would be to generate 3 random numbers between 0 and 255,
for each of the Red, Green and Blue components of the colour. Then you
could create your color using Color.FromArgb(Redpart, Greenpart,
Bluepart). That might give you control over the shades of colour you
generate by limiting the range of each of the components, if that's
what you want. You can also generate just one 32-bit random number,
and feed that to Color.FromArgb(bignumber).
 
Hello, Mark,

You could use the FromArgb method, as in the example below (that sets
the background color of a form containing a button):

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim RedValue As Integer = 255 * Rnd()
Dim GreenValue As Integer = 255 * Rnd()
Dim BlueValue As Integer = 255 * Rnd()
Dim RandomColor As Color
RandomColor = Color.FromArgb(RedValue, GreenValue, BlueValue)
Me.BackColor = RandomColor
End Sub

Cheers,
Randy
 
Hello, Mark,

You could use the FromArgb method, as in the example below (that sets
the background color of a form containing a button):

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim RedValue As Integer = 255 * Rnd()
Dim GreenValue As Integer = 255 * Rnd()

Rnd() is old vb, try the random class:


Public Class Form1

Private randomGenerator As Random
Private WithEvents t As Timer

Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
randomGenerator = New Random
t = New Timer
t.Interval = 50
t.Start()
End Sub

Private Sub t_Tick(ByVal sender As Object, ByVal e As
System.EventArgs) Handles t.Tick
' trigger paint
Me.Invalidate()
End Sub

Private Function randomColor() As Color
' array to hold 3 bytes
Dim rgb(2) As Byte
' fill the array with random bytes
randomGenerator.NextBytes(rgb)
' return a new color
Return Color.FromArgb(rgb(0), rgb(1), rgb(2))
End Function

Private Function randomPoint() As Point
Dim x As Integer = randomGenerator.Next(0, Me.ClientSize.Width +
1)
Dim y As Integer = randomGenerator.Next(0, Me.ClientSize.Height +
1)
Return New Point(x, y)
End Function

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As
System.Windows.Forms.PaintEventArgs) Handles Me.Paint
e.Graphics.DrawLine(New Pen(randomColor), randomPoint,
randomPoint)
End Sub

End Class
 
Back
Top