简体   繁体   中英

C# drawing line

So,i am working on a tic tac toe game for school ( project ) and i have this problem : 在此处输入图片说明

This is the code :

if (A1.Text == "x" && B2.Text == "x" && C3.Text == "x")
{
    l.DrawLine(p, 30, 48, 200, 150);
    p.Dispose();
}

How do i draw the line above those buttons ? I have all the functions in public void A1_Click(object sender, EventArgs e) because i use this for every button.

If the buttons are separate controls, there is no easy way to draw over them (at least while keeping them clickable). What you could do instead is draw the "buttons" yourself in the Form's Paint event handler, the same way you are (hopefully) already drawing the line. In this scenario, draw the line last and it'll go over the buttons. Doing things this way, of course, will require you to handle clicks yourself, so that when a user clicks somewhere in the Form's client area you figure out which "button" it's over and update the graphics accordingly.

As @ScottChamberlain suggested, here's some info on why you shouldn't do your drawing in click handlers:

Drawing glitches when using CreateGraphics rather than Paint event handler for custom drawing

Have you considered making your buttons transparent?

This worked for me (Made them all transparent/flat appearance).

Of course, you could always draw the lines on both the form repaint AND the buttons themselves so that it looks like one continuous line.

Alternatively, you could simply change the backcolor of the buttons to highlight the tic tac toe which may look better.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    if (allTrue()) //If tic tac toe is detected
        e.Graphics.DrawLine(new Pen(Color.Red, 10), new Point(0, 0), new Point(140, 100));
}

private void Form1_Click(object sender, EventArgs e)
{
    if (allTrue()) //If you click the form after we drew our line, reset
    {
        ab1 = false;
        ab2 = false;
        ab3 = false;
        this.Invalidate(); //We can call this whenever we want to redraw the form
    }
}

测试

属性

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