I have three labels and one button. I want to randomize the background color for label1 and label2, on the condition that not come the same color in label1 and label2, and with the click of a button I want to get label3 background color, which is a mixed color between label1 color and label2 color.
In my code i have colorlist with some colors.
I want to randomize colors that are included in my colorlist only
thanks for your help
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Create a List
Dim colorList As New List(Of SolidBrush)
' Add colors to it
'red
colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 0, 0)))
'white
colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 255, 255)))
'Blue
colorList.Add(New SolidBrush(Color.FromArgb(100, 0, 0, 255)))
'Yellow
colorList.Add(New SolidBrush(Color.FromArgb(100, 244, 255, 16)))
'Green
colorList.Add(New SolidBrush(Color.FromArgb(100, 0, 255, 0)))
'Pink
colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 16, 22)))
'Brown
colorList.Add(New SolidBrush(Color.FromArgb(100, 120, 37, 37)))
Dim rnd = New Random()
' Get a random item from the list between 0 and list count
Dim randomColour = colorList(rnd.Next(0, colorList.Count))
Dim randomColour1 = colorList(rnd.Next(0, colorList.Count))
' Assign the color to the label
Label1.BackColor = randomColour.Color
Label1.Text = randomColour.Color.Name.ToString
Label2.BackColor = randomColour1.Color
Label3.BackColor = (Color.FromArgb(Label1.BackColor.ToArgb + Label2.BackColor.ToArgb))
End Sub
You should not create a new Random class every time you click. Just make a class level variable.
Mixing the colors takes each component of the color (R,G, B) and averages the value. Then creates a new color from the averages.
The rest is pretty self explanatory.
You only need a List(Of Color)
Private rnd As New Random()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim colorList As New List(Of Color)
' Add colors to it
'red
colorList.Add(Color.FromArgb(255, 0, 0))
'white
colorList.Add(Color.FromArgb(255, 255, 255))
'Blue
colorList.Add(Color.FromArgb(0, 0, 255))
'Yellow
colorList.Add(Color.FromArgb(244, 255, 16))
'Green
colorList.Add(Color.FromArgb(0, 255, 0))
'Pink
colorList.Add(Color.FromArgb(255, 16, 22))
'Brown
colorList.Add(Color.FromArgb(120, 37, 37))
' Get a random item from the list between 0 and list count
Dim randomColour = colorList(rnd.Next(0, colorList.Count))
Dim randomColour1 = colorList(rnd.Next(0, colorList.Count))
' Get the name of the color to display in the label
Dim ColorName1 As String = GetColorName(randomColour.Name)
Dim ColorName2 As String = GetColorName(randomColour1.Name)
'Set the text color depending on the back color
If ColorName1 = "White" OrElse ColorName1 = "Yellow" Then
Label1.ForeColor = Color.Black
Else
Label1.ForeColor = Color.White
End If
If ColorName2 = "White" OrElse ColorName2 = "Yellow" Then
Label2.ForeColor = Color.Black
Else
Label2.ForeColor = Color.White
End If
'Set the back color and text of the labels.
Label1.BackColor = randomColour
Label1.Text = ColorName1
Label2.BackColor = randomColour1
Label2.Text = ColorName2
Label3.BackColor = MixColors(randomColour, randomColour1)
End Sub
Private Function MixColors(Color1 As Color, Color2 As Color) As Color
Dim r As Byte = CByte((Color1.R * 0.5) + (Color2.R * 0.5))
Dim g As Byte = CByte((Color1.G * 0.5) + (Color2.G * 0.5))
Dim b As Byte = CByte((Color1.B * 0.5) + (Color2.B * 0.5))
Return Color.FromArgb(r, g, b)
End Function
Private Function GetColorName(name As String) As String
Select Case name
Case "ffff0000"
Return "Red"
Case "ffffffff"
Return "White"
Case "ff0000ff"
Return "Blue"
Case "fff4ff10"
Return "Yellow"
Case "ff00ff00"
Return "Green"
Case "ffff1016"
Return "Pink"
Case "ff782525"
Return "Brown"
Case Else
Return "No match"
End Select
End Function
Related
In preparation for my Fall upcoming Adobe Illustrator class, where students always curse while learning the Pen tool and how to draw Bézier curves, I thought I'd provide them with some "theoretical foundation" outside of Illustrator. So far, I'm able to demonstrate the workings of a curve through four points described by x and y coordinates entered in a separate text boxes (see attached screen capture). My question, how can I "transform" this static demonstration into an interactive one, by allowing the students to "select" control points (shown in blue) and move them around the PictureBox? That's not a simple problem. Any pointers would be appreciated.
Here is my source code so far:
Public Class Form1
Dim Point1_X, Point1_Y, Point2_X, Point2_Y, Point3_X, Point3_Y, Point4_X, Point4_Y As Integer
Dim LignesDeDirection As Boolean
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LignesDeDirection = False
Point1_X = 100
Point1_Y = 100
Point2_X = 200
Point2_Y = 200
Point3_X = 50
Point3_Y = 250
Point4_X = 400
Point4_Y = 400
tbPoint1_X.Text = Point1_X
tbPoint1_Y.Text = Point1_Y
tbPoint2_X.Text = Point2_X
tbPoint2_Y.Text = Point2_Y
tbPoint3_X.Text = Point3_X
tbPoint3_Y.Text = Point3_Y
tbPoint4_X.Text = Point4_X
tbPoint4_Y.Text = Point4_Y
End Sub
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
e.Graphics.Clear(Color.LightGray)
Dim FondBlanc As New SolidBrush(Color.White)
e.Graphics.FillRectangle(FondBlanc, 0, 0, PictureBox1.Width, PictureBox1.Height)
Dim blackPen = New Pen(Color.FromArgb(128, 128, 128), 1)
Dim blackPen2pix = New Pen(Color.FromArgb(64, 64, 64), 2)
Dim EllipsePen = New Pen(Color.FromArgb(0, 128, 255), 3)
Dim blackPen3 = New Pen(Color.Black, 5.0F)
Dim blackPen2 = New Pen(Color.FromArgb(164, 164, 164), 1)
Dim CouleurPoint As New SolidBrush(Color.Magenta)
Dim CouleurControl As New SolidBrush(Color.Blue)
Dim Color2 = New Pen(Color.FromArgb(128, 128, 128), 1)
Dim PenBleu As New Pen(Color.Black, 2.0F)
PenBleu.EndCap = System.Drawing.Drawing2D.LineCap.Flat 'PenBleu.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor
PenBleu.CustomEndCap = New System.Drawing.Drawing2D.AdjustableArrowCap(8, 8)
Dim point1 As New Point(Point1_X, Point1_Y)
Dim point2 As New Point(Point2_X, Point2_Y)
Dim point3 As New Point(Point3_X, Point3_Y)
Dim point4 As New Point(Point4_X, Point4_Y)
e.Graphics.FillEllipse(CouleurPoint, Point1_X - 5, Point1_Y - 5, 10, 10)
e.Graphics.FillEllipse(CouleurControl, Point2_X - 5, Point2_Y - 5, 10, 10)
e.Graphics.FillEllipse(CouleurControl, Point3_X - 5, Point3_Y - 5, 10, 10)
e.Graphics.FillEllipse(CouleurPoint, Point4_X - 5, Point4_Y - 5, 10, 10)
Dim PenDashMagenta As New Pen(Color.Magenta, 1.5F)
PenDashMagenta.DashStyle = Drawing2D.DashStyle.Dash
Dim PenRéférence As New Pen(Color.ForestGreen, 1.0F)
If cbDirectionLines.Checked = True Then
LignesDeDirection = True
e.Graphics.DrawLine(PenRéférence, Point1_X, Point1_Y, Point2_X, Point2_Y)
e.Graphics.DrawLine(PenRéférence, Point3_X, Point3_Y, Point4_X, Point4_Y)
Else
LignesDeDirection = False
End If
e.Graphics.DrawEllipse(PenDashMagenta, Point1_X - 40, Point1_Y - 40, 80, 80)
e.Graphics.DrawEllipse(PenDashMagenta, Point4_X - 40, Point4_Y - 40, 80, 80)
e.Graphics.DrawBezier(PenBleu, point1, point2, point3, point4)
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Point1_X = tbPoint1_X.Text
Point1_Y = tbPoint1_Y.Text
Point2_X = tbPoint2_X.Text
Point2_Y = tbPoint2_Y.Text
Point3_X = tbPoint3_X.Text
Point3_Y = tbPoint3_Y.Text
Point4_X = tbPoint4_X.Text
Point4_Y = tbPoint4_Y.Text
PictureBox1.Invalidate()
End Sub
End Class
I have a Custom Control that displays color selections in a drop down and it works good.
I found the performance was poor with multiple controls on the same Form so I changed it to store the Color index in the Items collection.
This works good but the Designer gets populated with a large array of values and this causes empty items in the control.
How do I stop the designer from storing the Items?
Here is the designer code I don't want:
Me.cboCWarcColor.Items.AddRange(New Object()
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,
129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140}
)
Here is the Custom Control code:
Imports System.Collections.Generic
Public Class ColorCombo
Inherits System.Windows.Forms.ComboBox
Private mSelectedColor As Color = Nothing
Private Shared myColors As New List(Of Color)
Private Shared myColorsIndices As New List(Of Object)
Private Sub ColorCombo_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Me.DrawItem
Try
If e.Index < 0 Or e.Index >= myColors.Count Then
e.DrawBackground()
e.DrawFocusRectangle()
Exit Try
End If
' Get the Color object from the Items list
Dim aColor As Color = myColors.Item(e.Index) 'myColors.Item(e.Index)
' get a square using the bounds height
Dim rect As Rectangle = New Rectangle(4, e.Bounds.Top + 2, CInt(e.Bounds.Height * 1.5), e.Bounds.Height - 4)
' call these methods first
e.DrawBackground()
e.DrawFocusRectangle()
Dim textBrush As Brush
' change brush color if item is selected
If e.State = DrawItemState.Selected Then
textBrush = Brushes.White
Else
textBrush = Brushes.Black
End If
' draw a rectangle and fill it
Dim p As New Pen(aColor)
Dim br As New SolidBrush(aColor)
e.Graphics.DrawRectangle(p, rect)
e.Graphics.FillRectangle(br, rect)
' draw a border
rect.Inflate(1, 1)
e.Graphics.DrawRectangle(Pens.Black, rect)
' draw the Color name
e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit
e.Graphics.DrawString(aColor.Name, Me.Font, textBrush, rect.Width + 5, ((e.Bounds.Height - Me.Font.Height) \ 2) + e.Bounds.Top)
p.Dispose()
br.Dispose()
Catch ex As Exception
e.DrawBackground()
e.DrawFocusRectangle()
End Try
End Sub
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
Try
Dim aColorName As String
Me.BeginUpdate()
Items.Clear()
SelectedItem = Nothing
If myColors.Count = 0 Then
Dim names() As String = System.Enum.GetNames(GetType(System.Drawing.KnownColor))
For Each aColorName In names
If aColorName.StartsWith("Active") _
Or aColorName.StartsWith("Button") _
Or aColorName.StartsWith("Window") _
Or aColorName.StartsWith("Inactive") _
Or aColorName.StartsWith("HighlightText") _
Or aColorName.StartsWith("Control") _
Or aColorName.StartsWith("Scroll") _
Or aColorName.StartsWith("Menu") _
Or aColorName.StartsWith("Gradient") _
Or aColorName.StartsWith("App") _
Or aColorName.StartsWith("Desktop") _
Or aColorName.StartsWith("GrayText") _
Or aColorName.StartsWith("HotTrack") _
Or aColorName.StartsWith("Transparent") _
Or aColorName.StartsWith("Info") Then
Else
AddColor(Color.FromName(aColorName))
End If
Next
Else
Me.Items.AddRange(myColorsIndices.ToArray)
End If
Catch
Finally
Me.EndUpdate()
End Try
' Add any initialization after the InitializeComponent() call.
End Sub
Public Function AddColor(clr As Color) As Integer
myColors.Add(clr)
Dim idx As Integer = myColors.Count - 1
myColorsIndices.Add(idx)
Me.Items.Add(idx)
Return idx
End Function
''' <summary>
''' Returns a named color if one matches else it returns the passed color
''' </summary>
Public Function GetKnownColor(ByVal c As Color, Optional ByVal tolerance As Double = 0) As Color
For Each clr As Color In myColors
If ColorDistance(c, clr) <= tolerance Then
Return clr
End If
Next
Return c
End Function
''' <summary>
''' Returns index if one matches
''' </summary>
Public Function ContainsColor(ByVal c As Color) As Integer
Dim idx As Integer = 0
For Each clr As Color In myColors
If c.ToArgb = clr.ToArgb Then
Return idx
End If
idx += 1
Next
Return -1
End Function
Sub ColorCombo_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SelectedIndexChanged
If SelectedIndex >= 0 Then
mSelectedColor = myColors.Item(SelectedIndex)
End If
End Sub
Public Property SelectedColor() As Color
Get
'If mSelectedColor.Name = "Transparent" Then
' Return Color.Black
'End If
Return mSelectedColor
End Get
Set(ByVal value As Color)
Try
Dim smallestDist As Double = 255
Dim currentDist As Double = 0
Dim bestMatch As Integer = 0
Dim idx As Integer = -1
For Each c As Color In myColors
idx += 1
currentDist = ColorDistance(c, value)
If currentDist < smallestDist Then
smallestDist = currentDist
bestMatch = idx
End If
Next
If Me.Items.Count >= bestMatch Then
Me.SelectedIndex = bestMatch
End If
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Set
End Property
Private Function ColorDistance(ByRef clrA As Color, ByRef clrB As Color) As Double
Dim r As Long, g As Long, b As Long
r = CShort(clrA.R) - CShort(clrB.R)
g = CShort(clrA.G) - CShort(clrB.G)
b = CShort(clrA.B) - CShort(clrB.B)
Return Math.Sqrt(r * r + g * g + b * b)
End Function
End Class
Since you're adding the Color selection to the ComboBox.Items collection, the Form Designer serializes this this collection, adding all items to the Form.Designer.vb file. This also happens when you add Items a ComboBox using the Properties pane in the Designer: same effect.
You can instead set the DataSource of the ComboBox: it's faster and the object you add are not serialized. I also suggest not to add these values in the Control Constructor, but in the OnHandleCreated() override: the values are loaded only when the Control Handle is created, at run-time, so you don't load (not so useful) collections of items in the designer.
Since the handle can be recreated at run-time, more than once, there's a check for that (to avoid building the collection more than once).
Here, I'm using the ColorConverter's GetStandardValues() method to build a collection of known colors, excluding from the enumeration colors that have the IsSystemColor property set.
The collection is store in an array of Color objects, here named supportedColors.
You can also filter the collection returned by [Enum].GetValues() to get the same result, e.g.:
Dim colors As Color() = [Enum].GetValues(GetType(KnownColor)).OfType(Of KnownColor)().
Where(Function(kc) kc > 26 AndAlso kc < 168).
Select(function(kc) Color.FromKnownColor(kc)).ToArray()
SystemColors have Indexes < 27 and > 167 (I suggest not to rely on these values).
I've made a few changes to Custom Control:
When a Control is derived from an existing class, we don't subscribe to the events (e.g., DrawItem), we override the methods that rise the events (e.g., OnDrawItem()), then call base (MyBase) to rise the event (eventually, we can also not do that, if necessary). We are always one step ahead this way.
The drawing part needed some refactoring:
The Item's background actually was drawn 3 times
Disposable object should be declared with a Using statement, so we don't forget to dispose of them: very important when it comes to Graphics objects.
Replaced Graphics.DrawString() with TextRenderer.DrawText, to respect the original drawing.
Simplified the calculations: it's important to be as fast as possible here.
Thus also remove all Try/Catch blocks: costly and not really needed (don't use Try/Catch blocks when drawing, a few If conditions and some constraints - e.g., Math.Min(Math.Max()) - are better).
Also overridden OnMeasureItem() to change the height of the Items, set to Font.Height + 4 (pretty standard).
Other stuff you can see in the source code.
I've changed the SelectedColor custom property to be more reliable and to make it work with both OnSelectedIndexChanged() and OnSelectionChangeCommitted().
All Items represent a Color, so you can get the Color selected as, e.g.:
Private Sub ColorCombo1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ColorCombo1.SelectionChangeCommitted
SomeControl.BackColor = DirectCast(ColorCombo1.SelectedItem, Color)
' Or
SomeControl.BackColor = ColorCombo1.SelectedColor
End Sub
Modified the ComboBox Custom Control:
Remove what you have in Public Sub New and InitializeComponent(), it's not needed anymore.
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
Public Class ColorCombo
Inherits ComboBox
Private mSelectedColor As Color = Color.Empty
Private supportedColors As Color() = Nothing
Public Sub New()
DropDownStyle = ComboBoxStyle.DropDownList
DrawMode = DrawMode.OwnerDrawVariable
FlatStyle = FlatStyle.Flat
FormattingEnabled = False
' Set these just to show that the background color is important here
ForeColor = Color.White
BackColor = Color.FromArgb(32, 32, 32)
End Sub
Protected Overrides Sub OnHandleCreated(e As EventArgs)
MyBase.OnHandleCreated(e)
If DesignMode OrElse Me.Items.Count > 0 Then Return
supportedColors = New ColorConverter().GetStandardValues().OfType(Of Color)().
Where(Function(c) Not c.IsSystemColor).ToArray()
' Preserves a previous selection if any
Dim tmpCurrentColor = mSelectedColor
Me.DisplayMember = "Name"
Me.DataSource = supportedColors
If Not tmpCurrentColor.Equals(Color.Empty) Then
mSelectedColor = tmpCurrentColor
SelectedColor = mSelectedColor
End If
End Sub
Private flags As TextFormatFlags = TextFormatFlags.NoPadding Or TextFormatFlags.VerticalCenter
Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)
e.DrawBackground()
If e.Index < 0 Then Return
Dim itemColor = supportedColors(e.Index)
Dim colorRect = New Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Height - 2, e.Bounds.Height - 2)
Using colorBrush As New SolidBrush(itemColor)
e.Graphics.FillRectangle(colorBrush, colorRect)
Dim textRect = New Rectangle(New Point(colorRect.Right + 6, e.Bounds.Y), e.Bounds.Size)
TextRenderer.DrawText(e.Graphics, itemColor.Name, e.Font, textRect, e.ForeColor, Color.Transparent, flags)
End Using
e.DrawFocusRectangle()
MyBase.OnDrawItem(e)
End Sub
Protected Overrides Sub OnMeasureItem(e As MeasureItemEventArgs)
e.ItemHeight = Font.Height + 4
MyBase.OnMeasureItem(e)
End Sub
Protected Overrides Sub OnSelectedIndexChanged(e As EventArgs)
If SelectedIndex >= 0 Then mSelectedColor = supportedColors(SelectedIndex)
MyBase.OnSelectedIndexChanged(e)
End Sub
Protected Overrides Sub OnSelectionChangeCommitted(e As EventArgs)
mSelectedColor = supportedColors(SelectedIndex)
MyBase.OnSelectionChangeCommitted(e)
End Sub
Public Property SelectedColor As Color
Get
Return mSelectedColor
End Get
Set
mSelectedColor = Value
If Not IsHandleCreated Then Return
If mSelectedColor.IsKnownColor Then
SelectedItem = mSelectedColor
Else
If supportedColors Is Nothing Then Return
Dim smallestDist As Double = 255
Dim currentDist As Double = 0
Dim bestMatch As Integer = 0
Dim idx As Integer = -1
For Each c As Color In supportedColors
idx += 1
currentDist = ColorDistance(c, Value)
If currentDist < smallestDist Then
smallestDist = currentDist
bestMatch = idx
End If
Next
If supportedColors.Count >= bestMatch Then
mSelectedColor = supportedColors(bestMatch)
SelectedItem = mSelectedColor
End If
End If
End Set
End Property
Private Function ColorDistance(clrA As Color, clrB As Color) As Double
Dim r As Integer = CInt(clrA.R) - clrB.R
Dim g As Integer = CInt(clrA.G) - clrB.G
Dim b As Integer = CInt(clrA.B) - clrB.B
Return Math.Sqrt(r * r + g * g + b * b)
End Function
Public Function GetKnownColor(c As Color, Optional ByVal tolerance As Double = 0) As Color
For Each clr As Color In supportedColors
If ColorDistance(c, clr) <= tolerance Then Return clr
Next
Return c
End Function
Public Function ContainsColor(c As Color) As Integer
Dim idx As Integer = 0
For Each clr As Color In Me.Items
If c.ToArgb = clr.ToArgb Then Return idx
idx += 1
Next
Return -1
End Function
End Class
This is how it works:
I have a simple pixelsearch function searching for a certain Argb Color on screen.
This already works great and it finds the pixel with the color but I would like to add a Color Variation detection to it.
The Color of the pixel it should detect changes sometimes from (255, 100, 100, 100) to (255, 110, 94, 102) or something else (values are changing 10 points). Now the Pixelsearch function should have a Variationdetection so it would detect pixels with a near similar color so instead of only searching for color (255, 100, 100, 100) it should also search for (255, 101, 99, 102)... and more.
Is it possible to code that instead of Dim each Color and search for it?
Thats the code that I have already:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim xd3 = Color.FromArgb(255, 100, 100, 100) 'Searching for this color on the screen
Dim b As New Bitmap(2210, 1100) 'Position of Bitmap
Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(b)
g.CopyFromScreen(Me.Left, Me.Top, 0, 0, b.Size) 'Searching on Screen
For i = 0 To (Me.Width - 0) 'searching each pixel
For j = 0 To (Me.Height - 0) 'searching each pixel
If b.GetPixel(i, j) = xd3 Then 'If pixel has same color that im searching for it will show a messagebox true
MessageBox.Show("true")
End If
Next
Next
End Sub
I suggest something like this :
If Color_Is_In_The_Target_Variations(10, b.GetPixel(i, j), xd3) Then
MessageBox.Show("true")
End If
and
Private Function Color_Is_In_The_Target_Variations(variation As Integer, tested As Color, target As Color) As Boolean
If tested.R >= target.R - variation And tested.R <= target.R + variation And
tested.G >= target.G - variation And tested.G <= target.G + variation And
tested.B >= target.B - variation And tested.B <= target.B + variation Then
Return True
Else
Return False
End If
End Function
I'm trying to generate a random colour from 7 options. All of the stack overflow posts / tutorials I've found have been ANY random colour. This is the list of the colour :
Red = New SolidColorBrush(Color.FromArgb(100, 255, 0, 0))
White = New SolidColorBrush(Color.FromArgb(100, 255, 255, 255))
Blue = New SolidColorBrush(Color.FromArgb(100, 0, 0, 255))
Yellow = New SolidColorBrush(Color.FromArgb(100, 244, 255, 16))
Green = New SolidColorBrush(Color.FromArgb(100, 0, 255, 0))
pink = New SolidColorBrush(Color.FromArgb(100, 255, 16, 22))
Brown = New SolidColorBrush(Color.FromArgb(100, 120, 37, 37))
i want to randomthem to Label1.foreground :
Label1.Foreground = // I got Stuck at This -,-
I try to us a random number generator:
Dim randomColour As New Random
but I'm Stuck how to do that ... Pls Help Me ....
also you can use button when clicked color change in random
Public Class Form1
Dim rnd As New Random
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.BackColor = Color.FromArgb(255, rnd.Next(255), rnd.Next(255), rnd.Next(255))
End Sub
End Class
You may want to use SolidBrush.
' Create a List
Dim colorList As New List(Of SolidBrush)
' Add colors to it
colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 0, 0)))
colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 255, 255)))
...
' Create a random instance
Dim rnd = new Random()
' Get a random item from the list between 0 and list count
Dim randomColour = colorList(rnd.Next(0, colorList.Count))
' Assign the color to the label
Me.Label1.ForeColor = randomColour.Color
Sorry If my question is too long but I have to explain before I ask.
I want to change the text color of the cell when meet the condition I set.
I also want to draw the horizontal line in every 2 rows and vertical line in every 5 cols.
I can do both of them separately. The problem is I can't get them both at the same time.
If I change the text first, the borders of the affected cells have disappeared.
If I draw the border first, the text colors change back to black(default).
I have to change the text color and border color of the cells.
My Codes are as follows:
Private Sub GridBorderLine(ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs)
'Declare Border Style and Border Color
Dim vBStyle As ButtonBorderStyle = ButtonBorderStyle.Solid
Dim vBColor As Color = Color.Black
'Custom Row Border (Horizontal)
If e.RowIndex Mod 2 = False AndAlso e.RowIndex > 0 Then
e.Paint(e.CellBounds, DataGridViewPaintParts.All - DataGridViewPaintParts.ContentBackground)
Dim H As Integer = 0
ControlPaint.DrawBorder(e.Graphics, e.CellBounds, vBColor, 0, vBStyle, vBColor, 3, vBStyle, vBColor, 0, vBStyle, vBColor, 0, vBStyle)
e.Handled = True
End If
'Custom Column Border (Vertical)
If e.ColumnIndex Mod 5 = False AndAlso e.ColumnIndex > 0 Then
e.Paint(e.CellBounds, DataGridViewPaintParts.All - DataGridViewPaintParts.ContentBackground)
Dim W As Integer = 0
If e.RowIndex Mod 2 = False And e.RowIndex > 0 Then W = 3 Else W = 0
ControlPaint.DrawBorder(e.Graphics, e.CellBounds, vBColor, 3, vBStyle, vBColor, W, vBStyle, vBColor, 0, vBStyle, vBColor, 0, vBStyle)
e.Handled = True
End If
'Custom Cell Color
If e.FormattedValue.ToString.Contains(txt.Text) Then
CellColor(e)
End If
End Sub
Private Sub CellColor(ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs)
Dim vLength as Integer = txt.Text.Length
e.Paint(e.CellBounds, DataGridViewPaintParts.All - DataGridViewPaintParts.ContentForeground)
If e.FormattedValue.ToString = "" Then Exit Sub
Dim vBeginning As String = e.FormattedValue.ToString.Substring(0, vLength)
Dim vEnd As String = e.FormattedValue.ToString.Substring(vLength)
Dim s As Size = TextRenderer.MeasureText(e.FormattedValue.ToString, vFont)
Dim f As Size = TextRenderer.MeasureText(vBeginning, vFont)
Dim b As Size = TextRenderer.MeasureText(vEnd, vFont)
'Arrange Center Middle
Dim w = e.CellBounds.X + ((e.CellBounds.Width - s.Width) / 2)
Dim h = e.CellBounds.Y + ((e.CellBounds.Height - s.Height) / 2)
Dim topLeft As New Point(w, h)
Dim p As New Point(topLeft.X + (s.Width - b.Width), topLeft.Y)
TextRenderer.DrawText(e.Graphics, vBeginning, vFont, topLeft, Color.Red)
TextRenderer.DrawText(e.Graphics, vEnd, vFont, p, Color.Blue)
e.Handled = True
End Sub