65.9K
CodeProject 正在变化。 阅读更多。
Home

更改 MAC 按钮控件的图片颜色为任意颜色 (C#&VB.NET)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.22/5 (15投票s)

2006年6月23日

3分钟阅读

viewsIcon

68193

downloadIcon

5019

了解如何将按钮的图片更改为任何颜色,在本例中为 MACButton 控件。

引言

在 ‘ MAC-UI Suite ' 项目(一个包含超过 60 个具有 MAC 风格的 .NET UI 控件的丰富库)中,我们考虑创建一个类似于甚至优于 MAC 按钮的 3D 按钮。我们可以考虑两种方法:

(A) 通过代码绘制按钮。

(B) 使用图片。

方法 (A) 有两个局限性:

- 速度较慢:因为我们每次绘制都需要重绘按钮。对于复杂的绘制来说非常困难。

- 难以成为一个漂亮的按钮:正如您所知,即使使用 Photoshop 手工绘制也不容易。因此,用代码绘制会更加困难。

所以,我们喜欢方法 (B)。然而,方法 (A) 的一个优点是我们能为按钮设置任何颜色,因为我们控制了绘制代码。这让我想到为方法 (B) 提供支持:将图片按钮更改为任何颜色。请阅读我的解决方案如下。

代码内部

Graphics 类支持 DrawImage() 方法的很多重载列表,下面是其中之一。此方法的最后一个参数是 ImageAttributes imageAttrs .

[C#]

public void DrawImage(

Image image ,

Rectangle destRect ,

float srcX ,

float srcY ,

float srcWidth ,

float srcHeight ,

GraphicsUnit srcUnit ,

ImageAttributes imageAttrs

);

此参数指定了 image 对象的重新着色和伽马信息。我们可以用它来将按钮图片更改为任何颜色。

MAC 按钮支持按钮的不同状态的颜色:正常、悬停和禁用... 当绘制每个状态的图片时,我们使用一个与状态颜色对应的 ImageAttributes 对象。例如,当设置正常状态的颜色时,我们重新创建 iaNormal (ImageAttributes 对象),如下所示:

cmNormal = GetTranslationColorMatrix(buttonColorOrigin, buttonColorNormal);

iaNormal.SetColorMatrix( cmNormal, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

GetTranslationColorMatrix 方法在这里最有趣。它有两个参数:原始颜色 (originColor ) 和要转换到的新颜色 (newColor )。

/// <summary>

/// 获取将原始颜色转换为新颜色的 ColorMatrix

/// </summary>

private ColorMatrix GetTranslationColorMatrix(Color originColor, Color newColor)

{

// 使正常按钮变亮并降低饱和度的图像属性

ColorMatrix cmTrans = new ColorMatrix();

if(newColor.Equals(originColor))

return cmTrans;

float fTransRed = (float)newColor.R/(float)(originColor.R + originColor.G + originColor.B);

float fTransGreen = (float)newColor.G/(float)(originColor.R + originColor.G + originColor.B);

float fTransBlue = (float)newColor.B/(float)(originColor.R + originColor.G + originColor.B);

// 将原始颜色转换为新颜色

cmTrans.Matrix00 = fTransRed;

cmTrans.Matrix10 = fTransRed;

cmTrans.Matrix20 = fTransRed;

cmTrans.Matrix01 = fTransGreen;

cmTrans.Matrix11 = fTransGreen;

cmTrans.Matrix21 = fTransGreen;

cmTrans.Matrix02 = fTransBlue;

cmTrans.Matrix12 = fTransBlue;

cmTrans.Matrix22 = fTransBlue;

return cmTrans;

}

正如你所看到的,转换矩阵很简单,但它可以帮助我们将按钮图片更改为任何颜色。

结论

本文并非旨在构建一个好的按钮控件,它只是讨论如何将按钮的图片更改为任何颜色,在本例中为我的 MACButton 控件。

我们可以为此 MAC 按钮控件添加更多功能,例如:

  • 更多按钮样式。
  • 通过使用以下属性,快速选择按钮和文本的良好颜色样式:ColorStyleDefault、ColorStyleDisabled、ColorStyleHover、ColorStyleNormal。
  • 像 MAC X 按钮样式一样脉动。此外,您可以使用以下属性根据需要调整脉动:BrightnessDefault、PulseBrightnessMax、PulseBrightnessMin、Pulse、PulseInterval。
  • 通过以下属性为文本和图像提供更好的对齐方式和分配:ImageAlign、ImagePaddingX、ImagePaddingY、TextAlign、TextPaddingX、TextPaddingY。
  • 支持文本阴影。
  • 支持 Image 属性的 .ico 文件。
  • 支持 AcceptButton 或 CancelButton
  • 支持快捷键...
© . All rights reserved.