简体   繁体   中英

Lag when using graphics.drawline in winforms/C#

Beginner coder here getting into C#.. I'm making a program that involves drawing. Basically whenever I'm moving my mouse to draw, the actual line on the image appears delayed - and it's more.. straight, than it's supposed to be. It used to work fine, but at some point I guess something went wrong - can't remember what I did at the time so it's hard to retrace.. I tried to replicate just the drawing part of the program in a new solution, and it seems to work fine..

I'd post the .exe file so you can see what I mean but I'm not sure if we're allowed to post executables around here.

Edit: I've confirmed that the code works fine, look at the answer by sa_ddam213 for an example of the code. It seems as though it works fine in other peoples computers, so I'm completely confused.

Yo are creating a new Graphic and Pen object with every mouse move event, this will be a lot slower than creating these variables once in the Mouse_Down event.

Something like this may be a bit faster.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        b = new Bitmap(this.Width, this.Height);
    }

    private Graphics _graphics;
    private Pen _pen;
    private int pX = 0;
    private int pY = 0;
    private bool paint = false;
    private Bitmap b;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        pX = e.X;
        pY = e.Y;
        _graphics = Graphics.FromImage(b);
        _pen= new Pen(Color.Black, 3);
        paint = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (paint)
        {
            _graphics.DrawLine(_pen, pX, pY, e.X, e.Y);
            pictureBox1.BackgroundImage = b;
            pictureBox1.Refresh();
            pX = e.X;
            pY = e.Y;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        paint = false;
        _graphics.Dispose();
        _pen.Dispose();
    }
}

Instead of pictureBox1.Invalidate(), try using pictureBox1.Refresh()

You might also need to move it AFTER the pictureBox1.BackgroundImage = b

Also, in your MouseDown, you need to set this.Capture = true, and in your MouseUp you should set this.Capture = false . If you don't do that and you release the mouse button while your mouse cursor is over a different application, your's will never receive the MouseUp message.

May be It's a problem with your VGA . Check with another PC and let us know

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