简体   繁体   中英

How to correctly position a "X" in a rectangle?

I have the next problem: I have rectangle with 10 lines and 10 columns. When I press on a square I have to draw the "X" letter. Well, when I press on the right half, or on bottom half of the square, the "X" is drawn in the next right square, respectively in the below square. What should I do so when I press wherever on a square, the "X" to be drawn on the respective square?

My code is:

private void panel2_MouseClick(object sender, MouseEventArgs e)
{
    txtX.Text = Convert.ToString(e.X);
    txtY.Text = Convert.ToString(e.Y);

    var data = File.ReadAllLines(handleClinet.GetPath().Replace("Client","Server"));

    if (e.X >= 20 && e.Y >= 20 && e.X <= 220 && e.Y <= 220)
    {
            var graph = (sender as Panel).CreateGraphics();
            const int redInt = 255; //255 is example, give it what u know
            const int blueInt = 255; //255 is example, give it what u know
            const int greenInt = 255; //255 is example, give it what u know

            var p = new Pen(Color.FromArgb(redInt, blueInt, greenInt));
            var newEx = (int)Math.Round(
                (e.X / (double)20), MidpointRounding.AwayFromZero) * 20;

            var newEy = (int)Math.Round(
                (e.Y / (double)20), MidpointRounding.AwayFromZero) * 20;

            RectangleF rectF1 = new RectangleF(newEx, newEy, 20,20);
            graph.DrawString("X", new System.Drawing.Font("Arial", 16), Brushes.Blue, rectF1);
    }
}

And my rectangle is like:

在此处输入图片说明

Many thanks in advance!

It seems like the issue is where you are using your MidpointRounding.AwayFromZero

It seems to me that if the sum you have to calculate the position you want to draw the 'X' gives the result 6.6, you want to have it in position 6, not position 7, so realistically you would want to replace that line with:

int newEx = Math.Floor((e.X / (double)20)) * 20;

... And then do the same for the Y calculation too

This should ensure that whatever the result it gives, it should not jump to the next box.

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