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

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 -;
	Gdiplus::FontFamily fam(_T("Some family"));
	Gdiplus::Font* fo = new Gdiplus::Font(&fam,th,FontStyleRegular,UnitPixel);
	Gdiplus::RectF r1(r.left,,r.right - r.left,r.bottom -;
	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; = r2.Y;
	A.right = r2.X + r2.Width;
	A.bottom = r2.Y + r2.Height;
	delete fo;
	return A;

Open in new window

Who is Participating?
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

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));
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.