logo
CSharp_Graphics

Создание объекта Pen

При создании объекта Pen можно указать несколько атрибутов. Например, один из конструкторов Pen позволяет указывать при создании объекта его цвет и ширину. В приведенном ниже примере демонстрируется рисование синего отрезка толщиной 2 из точки с координатами (0, 0) в точку с координатами (60, 30).

Pen myPen = new Pen(Color.Blue, 2);

myGraphics.DrawLine(myPen, 0, 0, 60, 30);

Dashed Lines and Line Caps

The Pen object also exposes properties, such as DashStyle, that you can use to specify features of the line. The following example draws a dashed line from (100, 50) to (300, 80):

myPen.DashStyle = DashStyle.Dash;

myGraphics.DrawLine(myPen, 100, 50, 300, 80);

You can use the properties of the Pen object to set many more attributes of the line. The StartCap and EndCap properties specify the appearance of the ends of the line; the ends can be flat, square, rounded, triangular, or a custom shape. The LineJoin property lets you specify whether connected lines are mitered (joined with sharp corners), beveled, rounded, or clipped. The following illustration shows lines with various cap and join styles.

Drawing a Rectangle

Drawing rectangles with GDI+ is similar to drawing lines. To draw a rectangle, you need a Graphics object and a Pen object. The Graphics object provides a DrawRectangle method, and the Pen object stores attributes, such as line width and color. The Pen object is passed as one of the arguments to the DrawRectangle method. The following example draws a rectangle with its upper-left corner at (100, 50), a width of 80, and a height of 40:

myGraphics.DrawRectangle(myPen, 100, 50, 80, 40);

DrawRectangle is an overloaded method of the Graphics class, so there are several ways you can supply it with arguments. For example, you can construct a Rectangle object and pass the Rectangle object to the DrawRectangle method as an argument:

Rectangle myRectangle = new Rectangle(100, 50, 80, 40);

myGraphics.DrawRectangle(myPen, myRectangle);

A Rectangle object has methods and properties for manipulating and gathering information about the rectangle. For example, the Inflate and Offset methods change the size and position of the rectangle. The IntersectsWith method tells you whether the rectangle intersects another given rectangle, and the Contains method tells you whether a given point is inside the rectangle.