Created
January 15, 2022 11:03
-
-
Save X547/fe48f22ac6c93f75b42eb1f13c8d2cde to your computer and use it in GitHub Desktop.
FontSizeFromHeight implementation and sample code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <algorithm> | |
| #include <Application.h> | |
| #include <Window.h> | |
| #include <View.h> | |
| #include <Rect.h> | |
| float FontSizeFromHeight(BFont font, float height) | |
| { | |
| const int maxIterations = 16; | |
| const float precision = 1.0e-2f; | |
| float lo = 0.0f, hi = 2.0f * height; | |
| for (int i = 0; ; i++) { | |
| float m = (lo + hi) / 2.0f; | |
| font.SetSize(m); | |
| font_height fh; | |
| font.GetHeight(&fh); | |
| float val = fh.ascent + fh.descent; | |
| if (!(i < maxIterations) || std::abs(val - height) < precision) | |
| return m; | |
| if (val < height) | |
| lo = m; | |
| else | |
| hi = m; | |
| } | |
| } | |
| class TestView: public BView | |
| { | |
| public: | |
| TestView(BRect frame, const char *name): BView(frame, name, B_FOLLOW_NONE, B_FULL_UPDATE_ON_RESIZE | B_WILL_DRAW | B_SUBPIXEL_PRECISE) | |
| { | |
| } | |
| void Draw(BRect dirty) | |
| { | |
| BRect rect = Frame().OffsetToCopy(B_ORIGIN); | |
| float targetHeight = rect.Height() + 1; | |
| float fontSize = FontSizeFromHeight(be_plain_font, targetHeight); | |
| SetFontSize(fontSize); | |
| font_height fh; | |
| GetFontHeight(&fh); | |
| printf("targetHeight: %g\n", targetHeight); | |
| printf("size: %g\n", fontSize); | |
| printf("asc+dsc: %g\n", fh.ascent + fh.descent); | |
| DrawString("This is a test.", BPoint(0, fh.ascent)); | |
| } | |
| }; | |
| class TestWindow: public BWindow | |
| { | |
| private: | |
| TestView *fView; | |
| public: | |
| TestWindow(BRect frame): BWindow(frame, "TestApp", B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS) | |
| { | |
| fView = new TestView(frame.OffsetToCopy(B_ORIGIN), "view"); | |
| fView->SetResizingMode(B_FOLLOW_ALL); | |
| AddChild(fView, NULL); | |
| } | |
| void Quit() | |
| { | |
| be_app_messenger.SendMessage(B_QUIT_REQUESTED); | |
| BWindow::Quit(); | |
| } | |
| }; | |
| class TestApplication: public BApplication | |
| { | |
| private: | |
| TestWindow *fWnd; | |
| public: | |
| TestApplication(): BApplication("application/x-vnd.Test-App") | |
| { | |
| } | |
| void ReadyToRun() { | |
| fWnd = new TestWindow(BRect(0, 0, 512, 64).OffsetByCopy(64, 64)); | |
| fWnd->Show(); | |
| } | |
| }; | |
| int main() | |
| { | |
| TestApplication app; | |
| app.Run(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment