We help IT Professionals succeed at work.

Create the GDI+ font based on the given character height/width

WxW asked
Medium Priority
Last Modified: 2013-12-03
Hello there.

I have a font I want to use it for drawing, and I want to center a character of the font in a specific RECT I have. How do I create the font so when I draw the text, the character fits exactly (or almost) in the drawn area ? This is score drawing so the notes must be placed at exact positions.

This is the function I 've been using so far, but it either creates a very small font, or it doesn't center. The function has to work with any font character.

Best Regards.

RECT OutputNoteText(Gdiplus::Graphics* g,const wchar_t* x,int s,RECT& r,int th,Gdiplus::Brush* bx)
	RECT A = {0};
	// Create the note font
	if (th == 0)
		th = r.bottom - r.top;
	Gdiplus::FontFamily fam(_T("Some family"));
	Gdiplus::Font* fo = new Gdiplus::Font(&fam,th,FontStyleRegular,UnitPixel);
	Gdiplus::RectF r1(r.left,r.top,r.right - r.left,r.bottom - r.top);
	Gdiplus::RectF r2;
	Gdiplus::StringFormat sf;
	Gdiplus::SolidBrush br(Color(0,0,0));
	g->DrawString(x,s,fo,r2,&sf,bx ? bx : &br);
	A.left = r2.X;
	A.top = r2.Y;
	A.right = r2.X + r2.Width;
	A.bottom = r2.Y + r2.Height;
	delete fo;
	return A;

Open in new window

Watch Question

I've done this in c#, where I drew a number in the center of a rectangle.
Hope this helps

// C#
// here sectorWidth and sectorHeight would be your rectangles height and width
SizeF size = g.MeasureString(number.ToString(), font);
g.DrawString(number.ToString(), font, brush, new PointF(x * sectorWidth + sectorWidth / 2 - size.Width / 2, y * sectorHeight + sectorHeight / 2 - size.Height / 2));

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

One note to the above, x and y here was row and column number in a grid. You should replace x* sectorWidth and y * sectorHeight with your X and Y position for the rectangle.
Something like this:
g.DrawString(number.ToString(), font, brush, new PointF( your_X_position + sectorWidth / 2 - size.Width / 2, your_Y_position + sectorHeight / 2 - size.Height / 2));
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.