Or, just playing with VS 2005 and GDI+
A while back I received this question:
“I've been looking for a simple way to zoom in and out a hexagon using a trackbar in C# and I came across your article "Leverage New Graphics Capabilities" on ftponline, I think it's great... So could you please show me how to do it? The complete code would be very, very wonderful!”
I’ll admit, this has all the look of someone asking me to do their homework for a class. But I did need a good excuse to play around with the VS2005 Beta 2, so here goes.
The .NET Framework’s GDI+ has great support for the matrix transformations used to create affine transforms (scale, translate, rotate). The best part for beginning graphics programmers is that you probably don’t need to understand “affine transforms” or “matrix transformations”. The framework does, and you only need to tell it what you want. But just in case you’re curious, an affine transformation preserves lines and parallelism. (See here: http://www.geom.uiuc.edu/docs/reference/CRC-formulas/node15.html) A full treatment of the matrix transformations used in 2D geometry is here: http://www.geom.uiuc.edu/docs/reference/CRC-formulas/node3.html
Back to the problem at hand. The GDI+ transformation library gives me all the tools I need to make scaling and moving any drawing very simple. That also simplifies the math I need to use to create the shapes I want. I’ll define the hexagon to use 100% of a coordinate system from (-100, -100) to ( 100, 100):
private Point[] points = { new Point( -50,-100 ),
new Point( 50, -100 ),
new Point( 100, 0 ),
new Point( 50, 100 ),
new Point( 50, 100 ),
new Point( -50, 100 ),
new Point( -100, 0 ),
new Point( -50, -100) };
When I draw the hexagon, I need to translate the coordinate system to that the center of the window is the origin. One call to the TranslateTransform method does that:
e.Graphics.TranslateTransform((float )panel1.ClientSize.Width / 2,
( float ) panel1.ClientSize.Height / 2 );
Next, I need to scale the size of the hexagon based on the value of a trackbar. I used the VS.NET designer to set the trackbar value range at 10 to 100, meaning 10% of the window, to 100% of the window. One call to ScaleTransform modifies my coordinate system to match the chosen scale:
float scale = (float)this.trackBar1.Value / 100f;
e.Graphics.ScaleTransform(( float ) panel1.ClientSize.Width * scale/ 200f ,
(float )panel1.ClientSize.Height* scale / 200f);
The FillPolygon routine does that work of drawing for me:
e.Graphics.FillPolygon(Brushes.Red,
points);
And that’s it. Which brings me to one of the great qualities of .NET, and one that is consistently mis-represented by the MS marketing minions. It’s not about creating software without writing code. It’s about leveraging powerful concepts that have been developed, tested, and integrated into the framework. You’re able to accomplish more by writing more expressive and powerful code.
The sample
Get the code (vs2005 beta)