ゲームプログラム・サンプルプログラム集 (トップページに戻る)
文字列の描画(中央揃え)
実装イメージ

・初期化の所で文字列の描画幅を取得しています。
・描画の時にその幅の半分の長さ分左にずらして文字列を描画しています。
サンプルプログラム

#include "DxLib.h"

// 文字列の幅
int StrWidth0;
int StrWidth1;
int StrWidth2;

// ==============================
// *** 初期化処理 ***
// ==============================
void Game_Init()
{
	SetFontSize( 48 );
	ChangeFont( "MS P明朝" );

	// 各文字列の描画幅を取得
	StrWidth0 = GetDrawStringWidth( "文字列を", -1 );
	StrWidth1 = GetDrawStringWidth( "中央揃えにして", -1 );
	StrWidth2 = GetDrawStringWidth( "描画します", -1 );
}
// ==============================
// *** 更新処理 ***
// ==============================
void Game_Update()
{
}
// ==============================
// *** 描画処理 ***
// ==============================
void Game_Draw()
{
	DrawLine( 250, 0, 250, 200, GetColor( 255, 255, 255 ) );

	// 表示X座標を文字列の幅の半分ずらして文字列を描画
	DrawString( 250 - StrWidth0 / 2,  20, "文字列を", GetColor( 255, 255, 255 ) );
	DrawString( 250 - StrWidth1 / 2,  80, "中央揃えにして", GetColor( 255, 255, 255 ) );
	DrawString( 250 - StrWidth2 / 2, 140, "描画します", GetColor( 255, 255, 255 ) );
}
// ==============================
// *** 終了処理 ***
// ==============================
void Game_End()
{
}

// ******************************
// メイン関数
// ******************************
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	ChangeWindowMode( TRUE );
	SetGraphMode( 500, 200, 16 );
	if( DxLib_Init() == -1 ){
		return -1;
	}
	SetDrawScreen( DX_SCREEN_BACK );

	Game_Init();		// *** 初期化処理 ***

	while( ProcessMessage() == 0 && CheckHitKey( KEY_INPUT_ESCAPE ) == 0 ){
		Game_Update();	// *** 更新処理 ***

		ClearDrawScreen();
		Game_Draw();	// *** 描画処理 ***
		ScreenFlip();
	}

	Game_End();			// *** 終了処理 ***
	DxLib_End();
	return 0;
}