如何从字号得到字的高度和宽度?

解决方案 »

  1.   

    随便做了一个例子,你看看符合你的要求吗?unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        Procedure abc(iSize:Integer; var iWidth,iHeight:Integer);
      public
        { Public declarations }
      end;var
      Form1: TForm1;implementation{$R *.dfm}
    { TForm1 }procedure TForm1.abc(iSize: Integer; var iWidth, iHeight: Integer);
    var
      iOldSize:Integer;
    begin
      iOldSize:=Font.Size;
      try
        Font.Size:=iSize;    iWidth:=Canvas.TextWidth('A');
        iHeight:=Canvas.TextHeight('A');
      finally
        Font.Size:=iOldSize;
      end;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      iSize,iWidth,iHeight:Integer;
    begin
      iSize:=10;
      abc(iSize,iWidth,iHeight);
      ShowMessage(IntToStr(iSize)+'号字 宽度:'+IntToStr(iWidth)+' 高度:'+IntToStr(iHeight));
      iSize:=20;
      abc(iSize,iWidth,iHeight);
      ShowMessage(IntToStr(iSize)+'号字 宽度:'+IntToStr(iWidth)+' 高度:'+IntToStr(iHeight));
    end;end.
      

  2.   

    用相应的Canvas的TextWidth和TextHeight方法就可以了。相同的字号在不同的Canvas上得到的宽和高是不同的,与该Canvas关联的输出设备的分辨率有关。
      

  3.   

    const ErrorSize: SIZE = ( cx : -1; cy : -1 );function StringSize(DC: HDC; S: String): SIZE;
    begin
      if not Windows.GetTextExtentPoint32(DC, PChar(S), Length(S), Result) then
        Result := ErrorSize;
    end;function WindowStringSize(Handle: HWND; S: String): SIZE;
    var
      DC: HDC;
    begin
      DC := GetDC(Handle);
      if DC = 0 then
      begin
        Result := ErrorSize;
        Exit;
      end;
      
      Result := StringSize(DC, S);
      ReleaseDC(Handle, DC);
    end;function ControlStringSize(Control: TWinControl; S: String): SIZE;
    begin
      Result := WindowStringSize(Control.Handle, S);
    end;