【发布时间】:2009-08-06 19:36:29
【问题描述】:
是否可以在 winforms、vb.net 中定义将出现在 colordialog 的自定义颜色框中的特定自定义颜色?
【问题讨论】:
是否可以在 winforms、vb.net 中定义将出现在 colordialog 的自定义颜色框中的特定自定义颜色?
【问题讨论】:
简而言之,是的。 MSDN 涵盖了它here。问题是它不是通过Color 完成的 - 您需要将值作为 BGR 集处理 - 即每个整数都由颜色 00BBGGRR 组成,因此您将蓝色左移 16,绿色左移 8,然后使用红色“原样”。
我的 VB 很烂,但是在 C# 中,要添加紫色:
using (ColorDialog dlg = new ColorDialog())
{
Color purple = Color.Purple;
int i = (purple.B << 16) | (purple.G << 8) | purple.R;
dlg.CustomColors = new[] { i };
dlg.ShowDialog();
}
reflector 向我保证这类似于:
Using dlg As ColorDialog = New ColorDialog
Dim purple As Color = Color.Purple
Dim i As Integer = (((purple.B << &H10) Or (purple.G << 8)) Or purple.R)
dlg.CustomColors = New Integer() { i }
dlg.ShowDialog
End Using
【讨论】:
如果您想拥有超过 1 种自定义颜色,您可以这样做:
'Define custom colors
Dim cMyCustomColors(1) As Color
cMyCustomColors(0) = Color.FromArgb(0, 255, 255) 'aqua
cMyCustomColors(1) = Color.FromArgb(230, 104, 220) 'bright pink
'Convert colors to integers
Dim colorBlue As Integer
Dim colorGreen As Integer
Dim colorRed As Integer
Dim iMyCustomColor As Integer
Dim iMyCustomColors(cMyCustomColors.Length - 1) As Integer
For index = 0 To cMyCustomColors.Length - 1
'cast to integer
colorBlue = cMyCustomColors(index).B
colorGreen = cMyCustomColors(index).G
colorRed = cMyCustomColors(index).R
'shift the bits
iMyCustomColor = colorBlue << 16 Or colorGreen << 8 Or colorRed
iMyCustomColors(index) = iMyCustomColor
Next
ColorDialog1.CustomColors = iMyCustomColors
ColorDialog1.ShowDialog()
【讨论】:
现有示例包含错误。
purple.B 是一个字节而不是整数,因此将其移动 8 位或 16 位不会对值产生任何影响。每个字节首先必须转换为整数,然后再进行移位。像这样的东西(VB.NET):
Dim CurrentColor As Color = Color.Purple
Using dlg As ColorDialog = New ColorDialog
Dim colourBlue As Integer = CurrentColor.B
Dim colourGreen As Integer = CurrentColor.G
Dim colourRed As Integer = CurrentColor.R
Dim newCustomColour as Integer = colourBlue << 16 Or colourGreen << 8 Or colourRed
dlg.CustomColors = New Integer() { newCustomColour }
dlg.ShowDialog
End Using
【讨论】:
简化(基于 Gabby)
如果您知道目标自定义颜色的 ARGB,请使用:
' Define custom colors
ColorDialog1.CustomColors = New Integer() {(255 << 16 Or 255 << 8 Or 0), _
(220 << 16 Or 104 << 8 Or 230), _
(255 << 16 Or 214 << 8 Or 177)}
ColorDialog1.ShowDialog()
'where colors are (arbg) 1: 0,255,255 [aqua]
' 2: 230,104,220 [bright pink]
' 3: 177,214,255 [whatever]
【讨论】: