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

GlowButton - 发光按钮控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.70/5 (24投票s)

2010 年 2 月 24 日

CPOL

1分钟阅读

viewsIcon

71272

downloadIcon

4221

一个简单的媒体控制按钮

screen.png

一个小技巧...

最近我偶然发现了KMP Player软件,并查看了一些图形元素(如果你想看一些非常好的图形作品,我推荐你检查一下)。我为一个项目需要的一个元素是一个简单的发光按钮控件,用于播放器控件,没什么特别的,只是一个悬停时改变颜色并发光的图像。

让图像改变颜色相当简单,通过修改ImageAttribute的颜色矩阵来实现。

private void DrawColoredImage(Graphics g, Image img, Rectangle bounds, Color clr)
{
     using (ImageAttributes ia = new ImageAttributes())
     {
         ColorMatrix cm = new ColorMatrix();
         // convert and refactor color palette
         cm.Matrix00 = ParseColor(clr.R);
         cm.Matrix11 = ParseColor(clr.G);
         cm.Matrix22 = ParseColor(clr.B);
         cm.Matrix33 = ParseColor(clr.A);
         cm.Matrix44 = 1f;
         // set matrix
         ia.SetColorMatrix(cm);
         // draw
         g.DrawImage(img, bounds, 0, 0, img.Width, 
                     img.Height, GraphicsUnit.Pixel, ia);
     }
}

示例代码中的ParseColor 只是将 byte 转换为 float 值。

glow.jpg

获得发光效果也使用 ImageAttributes 类来实现。首先膨胀图像,然后更改颜色调色板和 Alpha 值,然后将干净的图像绘制在上面。所有这些都是通过首先将控件元素绘制到缓冲区位图中来实现的。

private void DrawButton()
{
    if (this.Image == null)
        return;

    Rectangle bounds = new Rectangle(0, 0, this.Width, this.Height);
    Rectangle imageBounds = GetImageBounds(bounds, this.Image);

    // draw into a buffer
    using (Graphics g = Graphics.FromImage(_bmpBuffer))
    {
        ...
    }
    // draw the buffer
    using (Graphics g = Graphics.FromHwnd(this.Handle))
        DrawImage(g, _bmpBuffer, bounds);
}

该控件提供了大部分属性的暴露,例如各种颜色状态,可选的焦点遮罩和边框。以下是属性列表

  • Checked:复选框状态
  • CheckedBorderColor:选中状态的边框颜色
  • CheckStyle:复选框样式
  • FocusedMask:绘制焦点遮罩
  • ImageDisabledColor:禁用状态的图像颜色
  • ImageFocusedColor:获得焦点状态的图像颜色
  • ImageGlowColor:边框发光颜色
  • ImageHoverColor:悬停状态的图像颜色
  • ImagePressedColor:按下状态的图像颜色
  • ImageGlowFactor:发光因子深度
  • FocusOnHover:悬停时获得焦点

历史

  • 2010年2月24日:初始发布
  • 2010年3月27日:文章截图和源代码
© . All rights reserved.