在UserControl上用画笔绘图

时间:2011-11-16 10:24:48

标签: c# winforms graphics

我试图在UserControl控件上使用画笔绘制。我可以绘制线条,圆形和矩形。我不明白为什么我不能用画笔画画。下面的代码让我只指向MouseDown然后它移动到MouseUp中设置的位置。 MouseMove期间没有绘制任何内容。我想我在这里不了解一些基本规则。

此代码适用于行:

public override void Draw(Graphics graphics) {
  graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
  graphics.DrawLine(new Pen(this.Color, this.PenSize), startPoint, endPoint);
}

这段代码我尝试适应刷子:

public override void Draw(Graphics graphics) {
  if (this.bitmap != null) {
    graphics = Graphics.FromImage(this.bitmap);
    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    graphics.DrawEllipse(new Pen(this.Color, this.PenSize), startPoint.X, startPoint.Y,
                         this.PenSize, this.PenSize);
    graphics.DrawImage(this.bitmap, 0, 0);
  }
}

此代码重新绘制对象列表:

private void UserControl_Paint(object sender, PaintEventArgs e) {
  if (ObjectsList != null) {
    ObjectsList.Draw(e.Graphics);
  }
}

正如代码所示,我试图在点状线绘制之前和之后抓取位图图像。我应该采取其他方式吗?

1 个答案:

答案 0 :(得分:2)

我真的不明白你的问题,但在你的第二段代码中,他们似乎是个错误。也许你应该尝试这个:

public override void Draw(Graphics graphics)
{
    if (this.bitmap != null)
    {
        Graphics g = Graphics.FromImage(this.bitmap);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.DrawEllipse(new Pen(this.Color, this.PenSize), startPoint.X, startPoint.Y, this.PenSize, this.PenSize);
        graphics.DrawImage(this.bitmap, 0, 0);
    }
}

否则,您将在位图本身上绘制位图。希望这会有所帮助。