Managing the State of a Graphics Object
A Graphics object has several properties that influence the quality of the items that are drawn. For example, you can set the TextRenderingHint property to specify the type of antialiasing (if any) applied to text. Other properties that influence quality are SmoothingMode, CompositingMode, CompositingQuality, and InterpolationMode.
A Graphics object maintains two transformations (world and page) that are applied to all items drawn by that Graphics object. Any affine transformation can be stored in the world transformation. Affine transformations include scaling, rotating, reflecting, skewing, and translating. The page transformation can be used for scaling and for changing units (for example, pixels to inches). For more information, see Coordinate Systems and Transformations.
The following example sets the world and page transformations of a Graphics object. The world transformation is set to a 30-degree rotation. The page transformation is set so that the coordinates passed to the second DrawEllipse will be treated as millimeters instead of pixels. The code makes two identical calls to the DrawEllipse method. The world transformation is applied to the first DrawEllipse call, and both transformations (world and page) are applied to the second DrawEllipse call.
Graphics graphics = e.Graphics; Pen pen = new Pen(Color.Red); graphics.ResetTransform(); graphics.RotateTransform(30); // world transformation graphics.DrawEllipse(pen, 0, 0, 100, 50); graphics.PageUnit = GraphicsUnit.Millimeter; // page transformation graphics.DrawEllipse(pen, 0, 0, 100, 50);
The following illustration shows the two ellipses. Note that the 30-degree rotation is about the origin of the coordinate system (upper-left corner of the client area), not about the centers of the ellipses. Also note that the pen width of 1 means 1 pixel for the first ellipse and 1 millimeter for the second ellipse.
The following example creates a plus-shaped region by forming the union of two rectangles. That region is designated as the clipping region of a Graphics object. Then the code draws two lines that are restricted to the interior of the clipping region.
Graphics graphics = e.Graphics; // Opaque red, width 5 Pen pen = new Pen(Color.Red, 5); // Opaque aqua SolidBrush brush = new SolidBrush(Color.FromArgb(255, 180, 255, 255)); // Create a plus-shaped region by forming the union of two rectangles. Region region = new Region(new Rectangle(50, 0, 50, 150)); region.Union(new Rectangle(0, 50, 150, 50)); graphics.FillRegion(brush, region); // Set the clipping region. graphics.SetClip(region, CombineMode.Replace); // Draw two clipped lines. graphics.DrawLine(pen, 0, 30, 150, 160); graphics.DrawLine(pen, 40, 20, 190, 150);
The following illustration shows the clipped lines.