在互联网上,有许多自定义的颜色选择器,包括在MSDN和Code Project上。虽然有很多类似的文章讨论自定义颜色选择器,但还没有看到有文章讨论如何将图像/位图转换为颜色选择器,所以决定尝试实现它,希望对CodeProject的成员有所帮助。
要从图像/位图中获取像素颜色,可以使用Bitmap类的GetPixel方法。首先需要定义一个Image对象,然后将像素的x和y坐标传递给GetPixel方法,这样就可以得到像素的颜色。以下是VB.NET的代码示例:
Dim bmp As New Bitmap("Grapes.jpg")
Dim x As Integer = 20
Dim y As Integer = 20
Dim pixelColor As Color = bmp.GetPixel(x, y)
这段代码首先创建了一个Bitmap对象,然后定义了要检索的像素的x和y坐标,最后通过GetPixel方法获取了像素的颜色。
图像颜色选择器的核心思想是将MouseDown和MouseMove事件的引用传递给一个私有方法,以获取鼠标位置,然后使用该点获取该点的颜色。
ImageColorPicker.vb:扩展了Windows.Forms.Control类。
Image:用于设置用户选择的图像/位图。
Public Property Image As Bitmap
Get
Return Me.originalBitmap
End Get
Set(ByVal value As Bitmap)
Me.originalBitmap = value
Me.DrawImage()
Me.Invalidate()
End Set
End Property
Color:获取选定的颜色。
Public Property Color As Color
Get
Return Me.selectedColor
End Get
Set(ByVal value As Color)
Me.selectedColor = value
Me.PixelColorToPoint()
Me.DrawImage()
MyBase.Invalidate()
End Set
End Property
ColorChanged:当图像像素颜色变化时发生,它也代表控件的DefaultEvent。
Public Custom Event ColorChanged As EventHandler
AddHandler(ByVal value As EventHandler)
Me.Events.AddHandler("ColorChangedEvent", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Me.Events.RemoveHandler("ColorChangedEvent", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
CType(Me.Events("ColorChangedEvent"), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
以下是一些关键的方法,包括绘制图像、获取像素颜色点、检查像素颜色点是否在指定的边界内等。
Private Sub DrawImage()
If MyBase.Width > 0 AndAlso Me.originalBitmap IsNot Nothing Then
Me.pickerBitmap = New Bitmap(MyBase.ClientRectangle.Width - _
(Me.controlBorder * 2), MyBase.ClientRectangle.Height - _
(Me.controlBorder * 2))
Dim g As Graphics = Graphics.FromImage(Me.pickerBitmap)
Dim mode As SmoothingMode = g.SmoothingMode
Dim rect As New Rectangle(0, 0, Me.pickerBitmap.Width, _
Me.pickerBitmap.Height)
g.DrawImage(Me.originalBitmap, rect)
g.SmoothingMode = mode
g.Dispose()
End If
End Sub
使用控件:
Public Class Form1
Private selectedColor As Color
Private Sub ImagColorPicker1_ColorChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ImagColorPicker1.ColorChanged
selectedColor = Me.ImagColorPicker1.Color
Me.Invalidate()
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaint(e)
e.Graphics.FillRectangle(New SolidBrush(Me.selectedColor), _
New Rectangle(0, 0, 30, 30))
End Sub
End Class