Visual C#

Applications Accessories: The Rectangle

The combination of the location and size of an object is represented as a rectangle: a geometric figure with four sides. To support this figure, the…

2 min read418 words4 code samples

Introduction#

The combination of the location and size of an object is represented as a rectangle: a geometric figure with four sides. To support this figure, the System.Drawing namespace provides the Rectangle and the RectangleF structures. A rectangle can be represented as follows:

A rectangle consists of four sides that meet at four right angles to form a geometric shape.

Characteristics of a Rectangle#

To completely represent it, a rectangle is defined by its location and it size. The location is defined by a point on the top-left corner of the rectangle:

  • The distance from the left border of the object that owns the rectangle to the left border of the rectangle is represented by a property called Left
  • The distance from the top border of the object that owns the rectangle to the top border of the rectangle is represented by a property called Top
  • The distance from the left to the right borders of the rectangle is represented by a property called Width
  • The distance from the left to the right borders of the rectangle is represented by a property called Height
  • The distance from the left border of the object that owns the rectangle to the right border of the rectangle is represented by a property called Right
  • The distance from the top border of the object that owns the rectangle to the bottom border of the rectangle is represented by a property called Bottom

You can define both the size and the position of a rectangle using the second Rectangle constructor. Its syntax is as follows:

To create a rectangle, you must provide at least its location and dimensions. The location can be represented by a Point value and the dimensions can be represented with a Size value. Based on this, you can use the following constructor to declare a Rectangle variable:

C#
public Rectangle(Point location, Size size);

The third constructor lets you initialize a rectangle by providing its location as a Point and its size as a Size object:

C#
public RectangleF(PointF location, SizeF size);

This constructor requires that you define a Point (or PointF) and a Size (or SizeF) in order to use it. If instead you know the integer values of the location and dimensions, you can use the following constructor to declare a Rectangle object:

C#
public Rectangle(int x, int y, int width, int height);

The equivalent RectangleF constructor has the following syntax:

C#
public RectangleF(float x, float y, float width, float height);

At any time, you can access or retrieve the characteristics of a Rectangle object as illustrated in the above picture from its properties. You use the same names we used in the picture. Home Copyright © 2010-2011 C# Key