0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++ builder > TLabel >Caption文字列を指定の枠におさめるためにFontサイズを自動調整

Last updated at Posted at 2016-11-16
動作環境
C++ Builder XE4

http://qiita.com/7of9/items/490f6b00b197f4e7df6e
の続き。

TLabelのCaptionに任意の文字列を代入するとき、フォームデザインで設計したTLabel.widthプロパティにおさまるようにフォントサイズを変更したい。

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 fntsiz[] = { 16, 14, 12, 10, 8}; // 大きいサイズから
	int size = sizeof(fntsiz) / sizeof(fntsiz[0]);

	bool widthIsOk;

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

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

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

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

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

	return (aftWdt < orgWdt);
}

qiita.png

ただし、こういう処理を多くのTLabelに対して行っていいかは要検討。
フォームに対して1つか2つ程度なら問題ないと考えている。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?