Measuring Characters Positions

Warning

The text API described in this topic is out of date. If you need to measure text using the new drawing engine in Graphics Mill, read the Fonts and Measuring Text article.

Graphics Mill provides the Font.GetCharacterPositions(String, Single) method which obtains each character position within a single-line text string drawn by the Graphics.DrawString method. It returns an array containing X coordinates of each character in the text string. If font tracking is modified with the Tracking property this is taken into account. The code example below demonstrates how to use this array to draw text on the curve:

Text on the curve

This image was produced with the following code:

C#
using (var bitmap = new Bitmap(300, 150, PixelFormat.Format24bppRgb, RgbColor.White))
using (var graphics = bitmap.GetGraphics())
{
   
const int centerX = 150;
   
const int centerY = 150;
   
const int radius = 110;

   
//Adjust font settings
   
var font = new Font("Times New Roman", 37);
    font
.VerticalAlignment = VerticalAlignment.Bottom;
    font
.HorizontalAlignment = HorizontalAlignment.Center;

   
var brush = new SolidBrush(RgbColor.Black);

   
string text = "Rounded sample text";

   
//Get characters positions
   
float[] positions = font.GetCharacterPositions(text, 0);
   
float strWidth = Graphics.MeasureString(text, font).Width;
   
float strHeight = Graphics.MeasureString(text, font).Height;

   
//Draw ellipse
    graphics
.DrawEllipse(new Pen(RgbColor.Black, 1), 40, 40, 220, 220);

   
//Draw character by character
   
for (int i = 0; i < text.Length; i++)
   
{
       
float charWidth = font.GetBlackBox(text[i]).Width;

       
//Compute angle to which rotate current character. Rotation will be
       
//performed relative to the middle of the bottom side of the character.
       
float angle = (float)(Math.PI - (positions[i] + charWidth / 2.0f) * Math.PI / strWidth);

       
//Compute the x and y coordinate of the character bottom
       
int x = (int)(centerX + radius * Math.Cos(angle));
       
int y = (int)(centerY - radius * Math.Sin(angle));

       
System.Drawing.Drawing2D.Matrix rotateMatrix = new System.Drawing.Drawing2D.Matrix();

       
//Convert angle from radians to degrees
       
float degAngle = (float)(angle / Math.PI * 180);

        rotateMatrix
.RotateAt(90 - degAngle, new System.Drawing.Point(x, y));

        graphics
.Transform = rotateMatrix;

        graphics
.DrawString(text[i].ToString(), font, brush, x, y);
   
}
    bitmap
.Save(@"Images\Output\MeasuringCharacter1.png");
}

See Also

Reference

Manual