Draw 2D or 3D borders in C#

The DrawBorder subroutine draws a border inside the edges of a Rectangle. If the border_style parameter is FixedSingle, the code subtracts 1 from the Rectangle's width and height so the border lies just inside the Rectangle and then draws the Rectangle as a flat, 2D border.

If border_style is Fixed3D, the code checks the sunken parameter and initializes an array to the system colors it should use for the different parts of the border. It then uses the Graphics object's DrawLine method to draw the border.


private void DrawBorder(Graphics gr, Rectangle rect, BorderStyle border_style, bool sunken)
{
switch (border_style)
{
case BorderStyle.FixedSingle:
rect.Width -= 1;
rect.Height -= 1;
gr.DrawRectangle(Pens.Black, rect);
break;
case BorderStyle.Fixed3D:
Color[] colors;
if (sunken)
{
colors = new Color[]
{
SystemColors.ControlDark,
SystemColors.ControlDarkDark,
SystemColors.ControlLightLight,
SystemColors.ControlLight
};
}
else
{
colors = new Color[]
{
SystemColors.ControlLightLight,
SystemColors.ControlLight,
SystemColors.ControlDark,
SystemColors.ControlDarkDark
};
}
using (Pen p = new Pen(colors[0]))
{
gr.DrawLine(p, rect.X, rect.Y + rect.Height - 1, rect.X, rect.Y);
gr.DrawLine(p, rect.X, rect.Y, rect.X + rect.Width - 1, rect.Y);
}
using (Pen p = new Pen(colors[1]))
{
gr.DrawLine(p, rect.X + 1, rect.Y + rect.Height - 2, rect.X + 1, rect.Y + 1);
gr.DrawLine(p, rect.X + 1, rect.Y + 1, rect.X + rect.Width - 2, rect.Y + 1);
}
using (Pen p = new Pen(colors[2]))
{
gr.DrawLine(p, rect.X, rect.Y + rect.Height - 1, rect.X + rect.Width - 1, rect.Y + rect.Height - 1);
gr.DrawLine(p, rect.X + rect.Width - 1, rect.Y + rect.Height - 1, rect.X + rect.Width - 1, rect.Y);
}
using (Pen p = new Pen(colors[3]))
{
gr.DrawLine(p, rect.X + 1, rect.Y + rect.Height - 2, rect.X + rect.Width - 2, rect.Y + rect.Height - 2);
gr.DrawLine(p, rect.X + rect.Width - 2, rect.Y + rect.Height - 2, rect.X + rect.Width - 2, rect.Y + 1);
}
break;
}
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.