
Over the last few days I have been playing with the Region property of a Form. As part of this I created a TextShapedForm that took on the shape of a string passed in on the constructor. Below is the code to shape the Form:
public void ShapeFormToString(string textShape) { int lineSpacing; // font family line spacing in design units int ascent; // the height of the font without line padding. float pixelsBetween; // space between lines in pixels
// Create a GraphicsPath object. GraphicsPath graphicsPath = new GraphicsPath();
// Set up the font. FontFamily fontFamily = new FontFamily("Arial"); FontStyle fontStyle = FontStyle.Bold; int emSize = 250; Font font = new Font(fontFamily, emSize, fontStyle, GraphicsUnit.Pixel);
Font = font; // set the font property
// Determining the space between lines lineSpacing = fontFamily.GetLineSpacing(fontStyle); ascent = fontFamily.GetCellAscent(fontStyle); pixelsBetween = font.Size * (ascent-lineSpacing) / fontFamily.GetEmHeight(fontStyle) + SystemInformation.CaptionHeight + SystemInformation.BorderSize.Height ;
// Move the starting point up so that it is positioned in the top right // of the client area (not inserting any space between lines) PointF pointF = new PointF(0, pixelsBetween + SystemInformation.CaptionHeight + SystemInformation.BorderSize.Height );
// Add the string to the graphics path. graphicsPath.AddString("Itron", fontFamily, (int)fontStyle, emSize, pointF, new StringFormat());
GraphicsPath = graphicsPath; // Set the region to the shape of the text this.Region = new Region(graphicsPath); }
As part of the process I also found the method that can return the size of a text string given the font. Check out MeasureString() method on the System.Drawing.Graphics class. The only drawback to this method is that I don't seem to be able to get hold of a Form's Graphic class from anywhere outside of the Paint event delegate.
A second thing I learned about was ascent and line spacing on fonts. The MSDN diagram below demonstrates these concepts the best.

Using this you can obviously determine the amount of space above a character. This is what I do in the "Determining the space between lines" code snippet above.
One last note, check Shaped .NET Windows Forms article by Markus Egger. (DevX may only enable you to see this as a Premier Club member but I found that if I refreshed enough times or accessed if from the CoDe Magazine site it worked.) Markus uses VB code and he hard codes his form size but none-the-less, it provides a good foundation for working with Form Regions and shaped forms.
12:33:58 AM
|