My goal is to implement a Form in which a crosshair is displayed whose center also marks the Form's center. When resizing the Form, the crosshair should be adjusted so that it continues to mark the center of the Form.
For this purpose I have written the following code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ResizeRedraw = true;
}
private void DrawCrosshair(Graphics g, Size size)
{
Pen pen = new Pen(Color.Black)
{
Width = 2
};
var halfWidth = Convert.ToInt32(size.Width / 2.0);
var halfHeight = Convert.ToInt32(size.Height / 2.0);
Point left = new Point(0, halfHeight);
Point right = new Point(size.Width - 1, halfHeight);
Point top = new Point(halfWidth, 0);
Point bottom = new Point(size.Height - 1, halfWidth);
g.DrawLine(pen, left, right);
g.DrawLine(pen, top, bottom);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawCrosshair(e.Graphics, Size);
}
}
Lines are drawn on the shape, but they are not placed correctly. In particular, the vertical line behaves strangely and gets painted partially crooked:
Did I calculate the coordinates in a wrong way? Or is there any other event that interferes with my drawing? I'm using .NET Framework 4.7.2.
You accidentally swapped the X, Y on the bottom point: new Point(size.Height - 1, halfWidth);
Try this instead:
Point bottom = new Point(halfWidth, size.Height - 1);