Drawing with brush on UserControl

2019-08-29 06:04发布

问题:

I am trying to draw with brush on UserControl control. I can draw lines, circles and rectangles. I don't exactly understand why I cannot draw with brush. The code below gives me just point on MouseDown and then it moves to the position set in MouseUp. There is no content drawn during MouseMove. I suppose that I do not understand some basic rule here.

This code works for lines:

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

This code I am trygin to adapt for brush:

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);
  }
}

This code repaints list of objects:

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

As the code presents I am trying to grab bitmap image before and after point-like line drawing. Should I do it other way?

回答1:

I don't really understand your question, but in your second code their seems to be a mistake. Maybe you should try this one:

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);
    }
}

Otherwise, you are drawing the bitmap on the bitmap itself. Hope this helps.