Unit1.cpp
上传用户:lhxd_sz
上传日期:2014-10-02
资源大小:38814k
文件大小:2k
源码类别:

VC书籍

开发平台:

C++ Builder

  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Unit1.h"
  5. //---------------------------------------------------------------------------
  6. #pragma package(smart_init)
  7. #pragma resource "*.dfm"
  8. TForm1 *Form1;
  9. //---------------------------------------------------------------------------
  10. __fastcall TForm1::TForm1(TComponent* Owner)
  11.         : TForm(Owner)
  12. {
  13. }
  14. //---------------------------------------------------------------------------
  15. void __fastcall TForm1::PaintText(TCanvas *cv,int x1,int y1,int x2,int y2,AnsiString text,int align)
  16. {
  17.   tagRECT drect;
  18.   int xx,yy,hh,ww,ll;
  19. //计算Y
  20.   hh=cv->TextHeight(text);
  21.   hh=y2-y1-hh;
  22.   hh/=2;
  23.   if(hh<0)hh=0;
  24.   yy=y1+hh;
  25. //超宽检查
  26.   ww=cv->TextWidth(text);
  27.   if(ww>(x2-x1))
  28.   {
  29.     for(;;)
  30.     {
  31.       if(cv->Font->Size<=8)break;
  32.       cv->Font->Size--;
  33.       ww=cv->TextWidth(text);
  34.       if(ww<=(x2-x1))break;
  35.     }
  36.   }
  37. //
  38.   ww=cv->TextWidth(text);
  39.   if(ww>(x2-x1))//如果再超宽
  40.   {
  41.     drect.left=x1;
  42.     drect.top=y1;
  43.     drect.right=x2;
  44.     drect.bottom=y2;
  45.     ll=text.Length();
  46.     DrawText(cv->Handle,text.c_str(),
  47.       ll,&drect,DT_WORDBREAK);
  48.   }
  49.   else//按对齐方式输出文本
  50.   {
  51.     if(align==0)//居左
  52.     {
  53.       xx=x1;
  54.     }
  55.     else if(align==2)//居右
  56.     {
  57.       ll=x2-x1-ww;
  58.       if(ll<0)ll=0;
  59.       xx=x1+ll;
  60.     }
  61.     else//居中
  62.     {
  63.       ll=x2-x1-ww;
  64.       ll/=2;
  65.       if(ll<0)ll=0;
  66.       xx=x1+ll;
  67.     }
  68.     cv->TextOut(xx,yy,text);
  69.   }
  70. }
  71. //---------------------------------------------------------------------------
  72. void __fastcall TForm1::Button1Click(TObject *Sender)
  73. {
  74.   int xx1,xx2,yy1,yy2;
  75.   xx1=20;
  76.   xx2=120;
  77.   yy1=20;
  78.   yy2=60;
  79.   Canvas->Brush->Color=clWhite;
  80.   Canvas->FillRect(TRect(xx1,yy1,xx2,yy2));
  81.   Canvas->Font->Size=12;
  82.   PaintText(Canvas,xx1,yy1,xx2,yy2,Edit1->Text,RadioGroup1->ItemIndex);
  83. }
  84. //---------------------------------------------------------------------------