C++ Builder XE4 > Font > TLabelのWidthに基づき、フォントサイズを自動計算し変更する (FMX実装からVCL実装への移植)


動作環境
C++ Builder XE4

概要

  • TLabelのフォントがある
  • 拡大縮小をする時に、フォントサイズが自動的に調整されると良い

参考

を参考に下記の変更を行った

  • FMX実装からVCL実装へ変更
  • [StoryHeadlineLabel]直接指定から関数化へ変更
  • WidthだけでなくHeightも考慮
    • Widthだけだと、拡大時に文字の上部しか見えなくなったため

実装 v0.1

Unit1.h
//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE で管理されるコンポーネント
    TEdit *E_labelWidth;
    TButton *Button1;
    TLabel *Label1;
    void __fastcall Button1Click(TObject *Sender);
private:    // ユーザー宣言
    void __fastcall TForm1::ShrinkFontToFitLabel( TCanvas * Canvas, TLabel * Label );
public:     // ユーザー宣言
    __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ShrinkFontToFitLabel( TCanvas * Canvas, TLabel * Label )
{
    // based on
    //   https://stackoverflow.com/questions/32829548/firemonkey-shrink-text-font-to-fit-in-tlabel
    // imported to [VCL] from [FMX]

    double InitialFontSize = 30;
    Canvas->Font->Size = InitialFontSize;
    Label->Font->Size = InitialFontSize;
    bool fits = false;
    do {
        double widthA = Canvas->TextWidth (Label->Caption);
        if (widthA > Label->Width - 35) {
            Label->Font->Size --;
            Canvas->Font->Size --;
        } else {
            fits = true;
        }
        if (Label->Font->Size < 6) {
            fits = true;
        }
    } while (!fits);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int prewid = Label1->Width;
    Label1->Width = StrToIntDef(E_labelWidth->Text, 10);

    float ratio = (float)Label1->Width / prewid;
    Label1->Height *= ratio;

    ShrinkFontToFitLabel(Label1->Canvas, Label1);
}
//---------------------------------------------------------------------------

動作例

フォントサイズ: 20

フォントサイズ: 80

フォントサイズ: 100

フォントサイズ: 130

フォントサイズ: 200

備考

35というマジックナンバーは使われている