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 - 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;
	g->MeasureString(x,s,fo,r1,&r2);
 
	Gdiplus::StringFormat sf;
	sf.SetLineAlignment(StringAlignmentCenter);
	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

LVL 6
WxWAsked:
Who is Participating?
 
BlomholmCommented:
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

0
 
BlomholmCommented:
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));
0
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.