简体   繁体   中英

Graphics.DrawLine issue

I'm using C# WinForms to make a painting program. However, I'm using the Graphics.DrawLine method, which works fine when I move my mouse. However, it draws a flawed line (and not a "full" one). Here's what I mean:

在此处输入图片说明

The left one is how it should look like. The right one is how it looks like when you quickly draw a line. I want the line drawn to be perfect, not flawed like in the picture. How can I do it? This is my code.

Graphics Graphic;
Pen myPen = new Pen(Color.Black, 1);
Point ep = new Point(0, 0);
Point sp = new Point(0, 0);
int k = 0;

private void panelPaint_MouseDown(object sender, MouseEventArgs e)
{
    myPen.Width = (float)numericWidth.Value;
    myPen.Color = pbCurrent.BackColor;

    sp = e.Location;

    if (e.Button == System.Windows.Forms.MouseButtons.Left)
        k = 1;
}

private void panelPaint_MouseMove(object sender, MouseEventArgs e)
{
    if (k == 1)
    {
        ep = e.Location;
        Graphic = panelPaint.CreateGraphics();
        Graphic.DrawLine(myPen, sp, ep);
    }

    sp = ep;
}

private void panelPaint_MouseUp(object sender, MouseEventArgs e)
{
    k = 0;
}

Soemthing like what Windows' Paint Brush is.

The problem is that you are drawing lots of small lines having a large width. The lines have straight edges and that's why you are getting some blank pixels between the lines.

I would suggest you use round start and end caps for your Pen object, like this:

myPen.StartCap = System.Drawing.Drawing2D.LineCap.Round;
myPen.EndCap = System.Drawing.Drawing2D.LineCap.Round;

Here is how it looks: The blue line is your code, the red line is drawn using round caps:

样品

By the way: turning on antialiasing (SmoothingMode) does not solve the problem. You can still see some of the missing pixels, though they are less visible:

抗锯齿样本

I think you need to try anti-aliasing

like this:

 Graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

You need to set the Smoothing Mode before drawing

Graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

This will smooth the corners of the Line,See the Difference between AA Line and Non AA Line

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM