【问题标题】:Painting on Windows Forms Control with System.Drawing.Graphics使用 System.Drawing.Graphics 在 Windows 窗体控件上绘画
【发布时间】:2013-09-05 01:36:33
【问题描述】:

我对此完全陌生,我正在使用 C# 开发 Windows 窗体应用程序,并想创建一个“LevelMeter”,在我的想法中,这是一个 ProgressBar,左上部分被一个三角形覆盖,颜色为窗体背景。所以基本上我只是想覆盖左上角来模仿一个电平表,比如 VLC Players 音量控制或类似的。

我的问题是,我如何在 Control 本身上绘画?我想创建一个 UserControl 并在完成后添加到我的项目中。我可以使用 SolidBrush 和 FillPolygon 在表单上绘画,但 MSDN 库在 ProgressBar.Paint 事件上注明:“此 API 支持 .NET Framework 基础结构,不打算直接从您的代码中使用。”那么有没有办法在 Control 上绘画?


好的:“永不放弃实验”的原则始终是正确的,这是我的解决方案:

我制作了一个自定义的 LevelMeter :控制并使用 FillPolygon 方法来绘制 LevelMeter 的三角形,在我的例子中只有 8 个不同的值,范围从 0 到 7,所以我绘制了 LevelMeter 的 7 个“部分”。

    protected override void OnPaint(PaintEventArgs pe)
    {
        if (this.valueNew > valueOld)
        {
            // increase, paint with green
            this.CreateGraphics().FillPolygon(new SolidBrush(Color.LawnGreen), new Point[] { p2Old, p3Old, p3New, p2New });
        }

        else
        {
            // decrease, paint with BackColor
            this.CreateGraphics().FillPolygon(new SolidBrush(this.BackColor), new Point[] { p2New, p3New, p3Old, p2Old });
        }
    }

为了避免每次值更改时清除和重新绘制 LevelMeter 导致的“闪烁”,我只重新绘制需要添加(绿色)或删除(表单的背景颜色)的部分。

【问题讨论】:

  • 如果您找到适合您的解决方案,您应该回答自己的问题。
  • 尝试将DoubleBuffered 设置为true,如果不是,它是Control 的属性(因此ProgressBar)。
  • 我已将 DoubleBuffered 设置为 true,它一直在闪烁。我需要从头开始制作我的自定义控件。

标签: c# winforms graphics controls paint


【解决方案1】:

您希望在自定义控件中覆盖 OnPaint(PaintEventArgs e)。这将使您能够访问用于在控件上进行自定义绘制的System.Drawing.Graphics(通过e.Graphics)对象。

Graphics 让您可以访问 ton 多种方法来完成所需的绘画。

例子:

public class MyControl : Control { 
  // ...
  protected override void OnPaint(PaintEventArgs e) { 
    base.OnPaint(e); // Important - makes sure the Paint event fires
    using (var pen = new Pen(Color.Black, 3)) { 
      e.Graphics.DrawRectangle(pen, 0, 0, this.Width, this.Height); 
    }
  }
}

【讨论】:

  • 感谢您提交建议。
  • 不幸的是,重写 OnPaint,不会在 ProgressBar 上绘制任何形状。 :(
猜你喜欢
  • 2012-04-12
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
相关资源
最近更新 更多