Introduction
I wanted to add a thin, grey line down the middle of a splitter control split handle (the bar down the middle that separates the two panels and lets the user change the ratio displayed). So, I needed the center of the Splitter rectangle:
private void splitContainer_Paint(object sender, PaintEventArgs e)
{
SplitContainer sc = sender as SplitContainer;
if (sc != null)
{
Graphics g = e.Graphics;
if (sc.Orientation == Orientation.Vertical)
{
g.DrawLine(Pens.LightGray,
(sc.SplitterRectangle.Left + sc.SplitterRectangle.Right) / 2,
sc.SplitterRectangle.Top,
(sc.SplitterRectangle.Left + sc.SplitterRectangle.Right) / 2,
sc.SplitterRectangle.Bottom);
}
else
{
g.DrawLine(Pens.LightGray,
sc.SplitterRectangle.Left,
(sc.SplitterRectangle.Top + sc.SplitterRectangle.Bottom) / 2,
sc.SplitterRectangle.Right,
(sc.SplitterRectangle.Top + sc.SplitterRectangle.Bottom) / 2);
}
}
}
But that is messy, and difficult to read.
Background
A much more readable version would be:
private void splitContainer_Paint(object sender, PaintEventArgs e)
{
SplitContainer sc = sender as SplitContainer;
if (sc != null)
{
Graphics g = e.Graphics;
if (sc.Orientation == Orientation.Vertical)
{
g.DrawLine(Pens.LightGray, sc.SplitterRectangle.CenterTop(), sc.SplitterRectangle.CenterBottom());
}
else
{
g.DrawLine(Pens.LightGray, sc.SplitterRectangle.CenterLeft(), sc.SplitterRectangle.CenterRight());
}
}
}
All I had to do was add some static methods to my StaticMethods utility controls class:
using System.Drawing;
namespace UtilityControls
{
public static class StaticMethods
{
public static Point Center(this Rectangle r)
{
return new Point((r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2);
}
public static Point CenterRight(this Rectangle r)
{
return new Point(r.Right, (r.Top + r.Bottom) / 2);
}
public static Point CenterLeft(this Rectangle r)
{
return new Point(r.Left, (r.Top + r.Bottom) / 2);
}
public static Point CenterBottom(this Rectangle r)
{
return new Point((r.Left + r.Right) / 2, r.Bottom);
}
public static Point CenterTop(this Rectangle r)
{
return new Point((r.Left + r.Right) / 2, r.Top);
}
}
}
Using the code
Just add the file and use the new Rectangle.Center, Rectangle.CenterLeft and so forth methods.
History
Keep a running update of any changes or improvements you've
made here.
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?