c++ builder > TLabel > 指定の枠におさまるString文字列の長さの取得 (5文字単位)


動作環境
C++ Builder XE4

関連 http://qiita.com/7of9/items/4caba5c87522aa410447
関連 http://qiita.com/7of9/items/490f6b00b197f4e7df6e

TLabelを用意した時、そこにどの長さまでString文字列を代入できるか確認したくなった。

以下のgetMaximumStringLength()を実装した。

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::Button1Click(TObject *Sender)
{
//  String kDummyString = L"START_jfkldsajkfjdklsajfkldjsklfjaksdljfkldsjalkjfsdk_END";

//  Label1->Caption = kDummyString;

    int mxlen = getMaximumStringLength(Label1);
    String msg = L"Maxsize:" + IntToStr(mxlen);
    OutputDebugString(msg.c_str());

//  fitWithDesignedWidth(Label1);


    int nop=1;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::fitWithDesignedWidth(TLabel *lblPtr)
{
    int fntsiz[] = { 16, 14, 12, 10, 8 }; // 大きいサイズから
    int size = sizeof(fntsiz) / sizeof(fntsiz[0]);

    bool widthIsOk;

    for(int idx=0; idx<size; idx++) {
        lblPtr->Font->Size = fntsiz[idx];
        widthIsOk = checkWidthIsLargeEnough(lblPtr);
        if (widthIsOk) {
            break;
        }
    }
}

int __fastcall TForm1::getMaximumStringLength(TLabel *lblPtr)
{
    static const int kMaxLoop = 8;
    static const int kIncrease = 5;

    bool widthIsOk;
    int maxLen = 10;

    lblPtr->Caption = L"1234567890";

    int loop = 0;
    while(loop < kMaxLoop) {
        lblPtr->Caption = lblPtr->Caption + L"SAAAE"; // [kIncrease]に合わせて文字を用意
        widthIsOk = checkWidthIsLargeEnough(lblPtr);
        if (widthIsOk == false) {
            lblPtr->Caption = lblPtr->Caption.SubString(0, lblPtr->Caption.Length() - kIncrease);
            break;
        }
        maxLen += kIncrease;
        loop++;
    }

    return maxLen;
}

bool __fastcall TForm1::checkWidthIsLargeEnough(TLabel *lblPtr)
{
    int orgWdt = lblPtr->Width;

    // to check
    lblPtr->AutoSize = true;
    int aftWdt = Label1->Width;

    // recover
    lblPtr->AutoSize = false;
    lblPtr->Width = orgWdt;

    return (aftWdt < orgWdt);
}
結果
デバッグ出力: Maxsize:30 プロセス Project1.exe (752)