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

脉冲按钮

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (56投票s)

2009年10月10日

CPOL

2分钟阅读

viewsIcon

120433

downloadIcon

7740

如何创建辐射脉冲的按钮。

The PulseButtonTest application

引言

本文演示了如何使用 .NET 2.0 和 GDI+ 创建具有动态元素(脉冲)的按钮。 该控件利用 .NET Framework 的 Button 类。

按钮状态

以下是不同的按钮状态

The different button states

MouseOver 仅显示白色(透明)边框,焦点显示为纯橙色。 按下状态与默认状态相同,但没有反射。

图形

以下是显示的按钮的不同元素

The graphic elements of the PulseButton

可以设置 ImageText 属性。 该按钮支持两种形状:圆形和矩形。 矩形可以有圆角。

架构

该控件由单个类 PulseButton 组成,该类继承自 System.Windows.Forms.Button

The PulseButton Class

Using the Code

要测试该按钮,只需下载演示项目并使用 Visual Studio 2008 构建它。
单击不同的 PulseButton 以在属性网格中引用它们。

以下是属性的简要说明

  • ButtonColorBottom - 中心底部的颜色
  • ButtonColorTop - 中心顶部的颜色
  • CornerRadious - 当 Shape 设置为矩形时,角的半径
  • FocusColor - 指示焦点的边框颜色
  • ForeColor - 文本的颜色
  • Interval - 定时器间隔,默认为 50 [ms](此属性不可浏览)
  • NumberOfPulses - 脉冲数,1 - 3 可获得最佳效果
  • PulseColor - 脉冲的颜色
  • PulseWidth - 脉冲的宽度 - 应小于控件宽度的一半
  • ShapeType - 圆形或矩形
  • PulseSpeed - 脉冲的速度,介于 0.1 - 2 之间的值看起来不错

代码

脉冲使用 System.Windows.Forms.Timer 更新。 渲染脉冲的例程如下所示

/// <summary>
/// Handles the pulse timer tick.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> 
/// instance containing the event data.</param>
private void PulseTimerTick(object sender, EventArgs e)
{
  pulseTimer.Enabled = false;
  InflatePulses();
  Invalidate();
  pulseTimer.Enabled = true;
}

/// <summary>
/// Inflates the pulses.
/// </summary>
private void InflatePulses()
{
  for (var i = 0; i < pulses.Length; i++)
    {
      pulses[i].Inflate(PulseSpeed, PulseSpeed);
      if (pulses[i].Width > Width || pulses[i].Height > Height || 
			pulses[i].X < 0 || pulses[i].Y < 0)
        pulses[i] = new RectangleF(pulseWidth, pulseWidth, 
		Width - 2 * pulseWidth, Height - 2 * pulseWidth);
      pulseColors[i] = Color.FromArgb((int)(Math.Min(pulses[i].X * 255 / 
					pulseWidth, 255)), PulseColor);
    }
}

脉冲使用 PulseSpeed 膨胀,当脉冲超过控件的边界时,大小将重置。 当脉冲移动到控件边缘时,颜色会变得更透明。

关注点

常规 Button 控件涵盖的内容远不止表面所见,因此我们通过继承它获得了很大的好处。 另一种可能性是从 ButtonBase 继承并实现 IButtonControl 以避免获得您不需要的东西,但这需要付出更多的努力。

历史

  • 2009 年 10 月 10 日:控件的第一个版本 1.0
  • 2015 年 6 月:WPF 版本可以在这里找到
© . All rights reserved.