15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Measuring Coordinates <strong>and</strong> areas ❘ OC11<br />

}<br />

Console.WriteLine("bottomRight = " + bottomRight);<br />

Console.WriteLine("Size = " + rectangleSize);<br />

code download PointsAndSizes.sln<br />

This code, running as a simple console application called PointsAndSizes, produces the output shown in<br />

Figure 48-4.<br />

figure 48-4<br />

Note that this output also shows how the ToString() method has been overridden in both Point <strong>and</strong> Size<br />

to display the value in {X,Y} format.<br />

It is also possible to subtract a Size from a Point struct to produce a Point struct, <strong>and</strong> you can add two<br />

Size structs together, producing another Size. It is not possible, however, to add a Point struct to another<br />

Point. Microsoft decided that adding Point structs does not conceptually make sense, <strong>and</strong> so it chose not<br />

to supply any overload to the + operator that would have allowed that.<br />

You can also explicitly cast a Point to a Size struct <strong>and</strong> vice versa:<br />

Point topLeft = new Point(10,10);<br />

Size s1 = (Size)topLeft;<br />

Point p1 = (Point)s1;<br />

With this cast, s1.Width is assigned the value topLeft.X, <strong>and</strong> s1.Height is assigned the value topLeft.Y.<br />

Hence, s1 contains (10,10). p1 will end up storing the same values as topLeft.<br />

Fectangle <strong>and</strong> rectanglef<br />

These structures represent a rectangular region (usually of the screen). Just as with Point <strong>and</strong> Size, only<br />

the Rectangle struct is considered here. RectangleF is basically identical except that the properties that<br />

represent dimensions all use float, whereas those of Rectangle use int.<br />

A Rectangle struct can be thought of as composed of a point, representing the top-left corner of the<br />

rectangle, <strong>and</strong> a Size struct, representing how large it is. One of its constructors actually takes a Point<br />

struct <strong>and</strong> a Size struct as its parameters. You can see this by rewriting the earlier code from the<br />

DrawShapes sample that draws a rectangle:<br />

Graphics dc = e.Graphics;<br />

Pen bluePen = new Pen(Color.Blue, 3);<br />

Point topLeft = new Point(0,0);<br />

Size howBig = new Size(50,50);<br />

Rectangle rectangleArea = new Rectangle(topLeft, howBig);<br />

dc.DrawRectangle(bluePen, rectangleArea);<br />

This code also uses an alternative override of Graphics.DrawRectangle(), which takes a Pen <strong>and</strong> a<br />

Rectangle struct as its parameters.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!