How to centre ( and fill ) text in wxRect using a dynamic font size Topic is solved

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
katuday
Earned some good credits
Earned some good credits
Posts: 134
Joined: Fri Aug 17, 2012 2:22 am

How to centre ( and fill ) text in wxRect using a dynamic font size

Post by katuday »

Windows 10.
Visual Studio 2017
wxWidgets-3.1.3

I want to draw text that fills a rectangle also centred. The font size
should be selected based on the text size ( single or mulitple lines )
relative to the size of the rectangle.

Code: Select all

std::wstring text = L"Hello, world!";

wxRect screen(0,0,1440,900);

wxFontInfo fi;
fi.Family(wxFONTFAMILY_ROMAN).Style(wxFONTSTYLE_NORMAL).Weight(wxFONTWEIGHT_NORMAL);
wxFont font(fi);

wxClientDC dc(this);
font.Scale(50); // Would want to determine the scale factor based in the size of text relative to wxRect
dc.SetFont(font);
wxRect text_rect(screen.x, screen.y, screen.width, screen.height * 0.45f);
dc.DrawLabel(text, text_rect, wxALIGN_CENTRE);
User avatar
doublemax
Moderator
Moderator
Posts: 19160
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

Re: How to centre ( and fill ) text in wxRect using a dynamic font size

Post by doublemax »

There is nothing in wxWidgets that does this for you automatically. Pick a random font size, use wxDC::GetMultiLineTextExtent to calculate the size that you get, compare it with the size that you want, calculate a correction factor for the font size. Repeat until you're close enough to the target size.
Use the source, Luke!
Nunki
Filthy Rich wx Solver
Filthy Rich wx Solver
Posts: 235
Joined: Fri Sep 14, 2012 8:26 am
Location: Kontich, Belgium
Contact:

Re: How to centre ( and fill ) text in wxRect using a dynamic font size

Post by Nunki »

Hi Katuday,

I have attached the GraphTools module of my toolbox (7zip format). Maybe not the best code around but it might give you an insight and set you on the way to your solution. The methods are for displaying text in any fontsize, aligned left, right, centered, with an angle if needed. Also with a bounding rectangle, the line will be split into several lines.

Hope this may be usefull for you.

Regards,
Nunki
Attachments
GraphTools.zip
(3.96 KiB) Downloaded 79 times
Post Reply