我有下一个问题:我有10行和10列的矩形。当我按下一个正方形时,我必须画出“X”字母。好吧,当我按下右半边或正方形的下半部分时,“X”在下一个正方形中分别绘制在下面的正方形中。当我按下正方形的任何地方时,我应该怎么做,在相应的广场上绘制“X”?
我的代码是:
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);
}
}
我的矩形就像:
非常感谢提前!
答案 0 :(得分:1)
问题似乎是您使用MidpointRounding.AwayFromZero
在我看来,如果总和你需要计算你想要绘制的位置&#39; X&#39;给出结果6.6,你想让它在位置6,而不是位置7,所以现实地你想要用以下代码替换它:
int newEx = Math.Floor((e.X / (double)20)) * 20;
...然后为Y计算做同样的事情
这应该确保无论结果如何,都不应该跳到下一个框。