Friday, June 12, 2009

Calculate font width with GDI+

http://www.eggheadcafe.com/community/aspnet/2/10911/heres-a-sample.aspx

public Bitmap Render()
{

Graphics g = Graphics.FromImage(_canvas); //painting surface. uses canvas.

Font font = new Font(_font, _fontStyle);

SolidBrush shadowBrush; //for painting text
SolidBrush textBrush;

int nCharsFitted; //this is how we know we have all of the characters on the canvas
int nLinesFilled; //this tells us how many lines the text uses

//antialias fonts.
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

//create new canvas and set the size
Size canvasSize = _canvas.Size;
SizeF canvasSizeF = new SizeF(_canvas.Width, _canvas.Height);

//specify formatting options
StringFormat stringFormat = new StringFormat();
stringFormat.FormatFlags = StringFormatFlags.FitBlackBox & StringFormatFlags.NoClip;
SizeF textSizeF = new SizeF(0,0);

//fit text
while (true)
{
//measure text
textSizeF = g.MeasureString(_zText, font, canvasSizeF, stringFormat, out nCharsFitted, out nLinesFilled );

//see if it fits
if ((canvasSizeF.Height >= textSizeF.Height) &
(canvasSizeF.Width >= textSizeF.Width) &
(nCharsFitted == _zText.Length) &
(nLinesFilled * font.Height <= canvasSizeF.Height)) { //text fits break; } else { //text doesn't fit. lower point size and try again. font = new Font(font.FontFamily, font.SizeInPoints - 1, font.Style); } } //set point for where to start drawing the text PointF textPoint; PointF shadowPoint; switch(_eAlignment) { case Engine.Imaging.Alignment.Center: textPoint = new PointF((canvasSizeF.Width - textSizeF.Width) / 2, 0); break; case Engine.Imaging.Alignment.Right: textPoint = new PointF(canvasSizeF.Width - textSizeF.Width, 0); break; default: textPoint = new PointF(0,0); break; } //apply shadow? if (_nShadowDepth > 0)
{
shadowPoint = new PointF(textPoint.X + _nShadowDepth, + _nShadowDepth);
shadowBrush = new SolidBrush(_shadowColor);
g.DrawString(_zText, font, shadowBrush, new RectangleF(shadowPoint , canvasSizeF), stringFormat);
}


//define brush with color to paint text with
textBrush = new SolidBrush(_textColor);

//apply text
g.DrawString(_zText, font, textBrush, new RectangleF(textPoint , canvasSizeF), stringFormat);


textBrush = null;
shadowBrush = null;
g = null;
stringFormat = null;

return _canvas;
}

Another one
http://social.msdn.microsoft.com/forums/en-US/vblanguage/thread/8b301d31-5b2c-4c6d-b78f-c0867dd0084e

No comments: